#include <bits/stdc++.h>
using namespace std;
int n, pre[1001] = {0}, nxt[1001] = {0}, p, w[1001][1001];
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 0; i < p; i++) {
    int t1, t2, t3;
    scanf("%d%d%d", &t1, &t2, &t3);
    pre[t2] = t1;
    nxt[t1] = t2;
    w[t1][t2] = t3;
  }
  int ans = 0;
  for (int i = 1; i <= n; i++)
    if (pre[i] == 0 && nxt[i]) ans++;
  int tmp;
  printf("%d\n", ans);
  for (int i = 1; i <= n; i++)
    if (pre[i] == 0 && nxt[i]) {
      tmp = 1e9;
      int cur = i;
      while (nxt[cur] != 0) {
        tmp = min(tmp, w[cur][nxt[cur]]);
        cur = nxt[cur];
      }
      printf("%d %d %d\n", i, cur, tmp);
    }
  return 0;
}
