#include <bits/stdc++.h>
using namespace std;
long long n, p, i, j, res, minn, p1, k, c2[100010], c3[100010], ans[100010],
    ans1[100010], ans2[100010], c[100010], c1[100010], a[100010], b[100010],
    d[100010];
int main() {
  scanf("%I64d %I64d", &n, &p);
  for (i = 1; i <= n; i++) {
    c1[i] = 0;
    c3[i] = 0;
  }
  for (i = 1; i <= p; i++) {
    scanf("%I64d %I64d %I64d", &a[i], &b[i], &d[i]);
    c[a[i]] = b[i];
    c1[a[i]] = d[i];
    c2[b[i]] = 1;
  }
  for (i = 1; i <= n; i++) {
    minn = 0;
    if ((!c2[i]) && (c[i] != 0)) {
      minn = c1[i];
      j = c[i];
      p1 = 0;
      while (c[j] != 0) {
        c3[j] = 1;
        if (c1[j] < minn) minn = c1[j];
        j = c[j];
        if (c3[j]) {
          p1 = 1;
          break;
        }
      }
      if (!p1) {
        res++;
        ans[res] = i;
        ans1[res] = j;
        ans2[res] = minn;
      }
    }
    for (k = 1; k <= n; k++) c3[k] = 0;
  }
  printf("%d\n", res);
  for (i = 1; i <= n; i++)
    if ((ans[i] != 0) && (ans1[i] != 0) && (ans2[i] != 0))
      printf("%I64d %I64d %I64d \n", ans[i], ans1[i], ans2[i]);
  return 0;
}
