#include <bits/stdc++.h>
using namespace std;
int visit2[1050];
int visit3[1050];
int a[1050][1050];
int b[1050];
int c[1050][3];
int main() {
  ios::sync_with_stdio(false);
  memset(visit2, 0, sizeof(visit2));
  memset(a, 0, sizeof(a));
  memset(b, 0, sizeof(b));
  memset(visit3, 0, sizeof(visit3));
  int n, p, ans, x, y, d, id, q;
  int t = 0;
  bool flag = true;
  cin >> n >> p;
  for (int i = 0; i < p; i++) {
    cin >> x >> y >> d;
    a[x][y] = d;
    b[x] = y;
    visit2[x]++;
    visit3[y] = 1;
  }
  for (int i = 1; i <= n; i++) {
    if (visit3[i] != 1) {
      flag = false;
      break;
    }
  }
  if (flag) {
    cout << "0";
    return 0;
  } else {
    for (int i = 1; i <= n; i++) {
      ans = 1000050;
      if ((visit2[i]) && (!visit3[i])) {
        t++;
        q = i;
        while (b[q]) {
          visit2[b[q]] = 0;
          ans = min(ans, a[q][b[q]]);
          q = b[q];
          id = q;
        }
        visit2[i] = 0;
        c[t][0] = i;
        c[t][1] = id;
        c[t][2] = ans;
      }
    }
  }
  cout << t << endl;
  for (int i = 1; i <= t; i++) {
    cout << c[i][0] << " " << c[i][1] << " " << c[i][2] << endl;
  }
  return 0;
}
