#include <bits/stdc++.h>
using namespace std;
int adj[100001];
int weight[1001][1001], out[1001], in[1001];
int main() {
  int n, i, j, k, p, y = 0;
  cin >> n >> p;
  for (i = 0; i < p; i++) {
    int a, b, d;
    cin >> a >> b >> d;
    a--, b--;
    adj[a] = b;
    weight[a][b] = d;
    out[a]++;
    in[b]++;
  }
  for (i = 0; i < n; i++) {
    if (!in[i] && out[i]) y++;
  }
  cout << y << endl;
  for (j = 0; j < n; j++) {
    i = j;
    if (out[i] && !in[i]) {
      int u = 2e9;
      while (out[i]) {
        u = min(u, weight[i][adj[i]]);
        i = adj[i];
      }
      cout << j + 1 << ' ' << i + 1 << ' ' << u << endl;
    }
  }
}
