#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, next[2000], i, j, gt[2000], mmin, a1[2000], a2[2000], a3[2000], t;
  bool ra[2000], vao[2000];
  cin >> n >> m;
  memset(ra, false, sizeof(ra));
  memset(vao, false, sizeof(vao));
  for (i = 1; i <= m; i++) {
    cin >> a1[i] >> a2[i] >> a3[i];
    ;
    next[a1[i]] = a2[i];
    gt[a1[i]] = a3[i];
    ra[a1[i]] = true;
    vao[a2[i]] = true;
  }
  t = 0;
  for (i = 1; i <= n; i++)
    if (vao[i] == false && ra[i] == true) t++;
  cout << t << endl;
  for (i = 1; i <= n; i++)
    if (vao[i] == false && ra[i] == true) {
      j = i;
      mmin = 1000000000;
      while (ra[j] == true) {
        mmin = min(mmin, gt[j]);
        j = next[j];
      }
      cout << i << " " << j << " " << mmin << endl;
    }
}
