#include <bits/stdc++.h>
using namespace std;
struct point {
  int e, d, flag;
};
point p[1005];
struct point2 {
  int s, e, d;
};
point2 ans[1005];
int check[1005];
int top;
int main() {
  int s, e, d, i, m, n, t;
  while (scanf("%d%d", &n, &m) != EOF) {
    top = 0;
    memset(check, 0, sizeof(check));
    for (i = 0; i <= 1000; i++) p[i].flag = 0;
    for (i = 0; i < m; i++) {
      scanf("%d%d%d", &s, &e, &d);
      p[s].e = e;
      p[s].d = d;
      p[s].flag = 1;
      check[e] = 1;
    }
    for (i = 1; i <= n; i++) {
      if (p[i].flag == 1) {
        t = i;
        m = p[i].d;
        if (check[t] == 1) continue;
        do {
          p[t].flag = 0;
          if (m > p[t].d) m = p[t].d;
          t = p[t].e;
          if (p[t].flag == 0) break;
        } while (true);
        ans[top].s = i;
        ans[top].e = t;
        ans[top].d = m;
        top++;
      }
    }
    printf("%d\n", top);
    for (i = 0; i < top; i++)
      printf("%d %d %d\n", ans[i].s, ans[i].e, ans[i].d);
  }
  return 0;
}
