#include <bits/stdc++.h>
using namespace std;
int tap, minn, n, p, d[5000009], in[5000009], g[5000009];
void dfs(int v) {
  if (g[v]) {
    minn = min(minn, d[v]);
    dfs(g[v]);
  } else {
    tap = v;
  }
}
int main() {
  int a, b, c, count = 0;
  cin >> n >> p;
  for (int i = 1; i <= p; i++) {
    cin >> a >> b >> c;
    d[a] = c;
    in[b]++;
    g[a] = b;
  }
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0 && g[i] != 0) {
      count++;
    }
  }
  cout << count << endl;
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0 && g[i] != 0) {
      tap = -1;
      minn = 1e9;
      dfs(i);
      cout << i << " " << tap << " " << minn << endl;
    }
  }
}
