#include <bits/stdc++.h>
using namespace std;
const int inf = 2000000000;
int n, m, x, y, z, h[1005][2], q[1005][3], w;
bool b[1005];
int main() {
  scanf("%d%d", &n, &m);
  memset(h, -1, sizeof(h));
  memset(b, true, sizeof(b));
  while (m--) {
    scanf("%d%d%d", &x, &y, &z);
    h[x][0] = y;
    h[x][1] = z;
    b[y] = false;
  }
  w = 0;
  for (int i = 1, j; i <= n; i++) {
    if ((b[i]) && (h[i][0] != -1)) {
      int mi = inf;
      for (j = i; h[j][0] != -1; j = h[j][0]) {
        mi = min(mi, h[j][1]);
      }
      q[w][0] = i;
      q[w][1] = j;
      q[w][2] = mi;
      w++;
    }
  }
  printf("%d\n", w);
  for (int i = 0; i < w; i++) printf("%d %d %d\n", q[i][0], q[i][1], q[i][2]);
  return 0;
}
