#include <bits/stdc++.h>
using namespace std;
int mp[1005][1005];
int dc[1005][2], n, cnt, res[1005][3], x, y;
int find(int u) {
  int i;
  for (i = 0; i < n; i++) {
    if (mp[u][i] != -1) break;
  }
  if (i == n) {
    y = u;
    if (!dc[u][0] && dc[u][1]) return 1;
    return 0;
  } else {
    x = min(x, mp[u][i]);
    return find(i);
  }
}
int main() {
  int i, p, a, b, d;
  while (scanf("%d%d", &n, &p) == 2) {
    memset(mp, -1, sizeof(mp));
    for (i = 0; i < p; i++) {
      scanf("%d%d%d", &a, &b, &d);
      a--;
      b--;
      dc[a][0] = 1;
      dc[b][1] = 1;
      mp[a][b] = d;
    }
    cnt = 0;
    for (i = 0; i < n; i++) {
      if (dc[i][0] && !dc[i][1]) {
        x = 1 << 29;
        a = find(i);
        if (a) {
          res[cnt][0] = i + 1;
          res[cnt][1] = y + 1;
          res[cnt][2] = x;
          cnt++;
        }
      }
    }
    printf("%d\n", cnt);
    for (i = 0; i < cnt; i++) {
      printf("%d %d %d\n", res[i][0], res[i][1], res[i][2]);
    }
  }
  return 0;
}
