#include <bits/stdc++.h>
using namespace std;
struct s {
  int z, l;
} e[1010];
struct ss {
  int a, b, l;
} aa[1010];
bool flag[1010], flag1[1010];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int a, b, l;
    scanf("%d%d%d", &a, &b, &l);
    flag1[b] = 1;
    e[a].z = b;
    e[a].l = l;
  }
  int ans = 0;
  for (int i = 1; i <= n; i++)
    if (flag[i] == 0 && flag1[i] == 0 && e[i].z != 0) {
      ans++;
      flag[i] = 1;
      aa[ans].a = i;
      int temp = i, len = 10000000;
      while (e[temp].z != 0) {
        flag[temp] = 1;
        if (e[temp].z == aa[ans].a) {
          ans--;
          goto ee;
        }
        if (e[temp].l < len) len = e[temp].l;
        temp = e[temp].z;
      }
      flag[temp] = 1;
      aa[ans].b = temp;
      aa[ans].l = len;
    ee:;
    }
  printf("%d\n", ans);
  for (int i = 1; i <= ans; i++)
    printf("%d %d %d\n", aa[i].a, aa[i].b, aa[i].l);
}
