#include <bits/stdc++.h>
int a[1111], v[1111];
char hash[1111];
int main() {
  int i, j, n, m, x, y, z, o = 0;
  scanf("%d%d", &n, &m);
  for (i = 1; i <= m; i++) {
    scanf("%d%d%d", &x, &y, &z);
    a[x] = y;
    hash[y] = 1;
    v[x] = z;
  }
  for (i = 1; i <= n; i++) o += (!hash[i] && a[i]);
  printf("%d\n", o);
  for (i = 1; i <= n; i++)
    if (!hash[i] && a[i]) {
      m = 1000000000;
      for (j = i; a[j]; j = a[j]) m = ((m) < (v[j]) ? (m) : (v[j]));
      printf("%d %d %d\n", i, j, m);
    }
  return 0;
}
