#include <bits/stdc++.h>
using namespace std;
int n, p;
int to[1005];
int liu[1005][1005];
int outd[1005], ind[1005];
struct PI {
  int a, b, liu;
} P[1005];
int main(int argc, char *argv[]) {
  int k;
  while (scanf("%d%d", &n, &p) == 2) {
    memset(to, -1, sizeof(to));
    memset(liu, -1, sizeof(liu));
    memset(outd, 0, sizeof(outd));
    memset(ind, 0, sizeof(ind));
    for (int i = 0; i < p; i++) {
      int a, b, d;
      scanf("%d%d%d", &a, &b, &d);
      to[a] = b;
      outd[a]++;
      ind[b]++;
      liu[a][b] = d;
    }
    int u = 0, mn = 1000009;
    for (int i = 1; i <= n; i++) {
      if (ind[i] == 0) {
        mn = 1000009;
        P[u].a = i;
        int tem = i;
        while (to[tem] != -1) {
          if (mn > liu[tem][to[tem]]) mn = liu[tem][to[tem]];
          tem = to[tem];
        }
        P[u].b = tem;
        P[u++].liu = mn;
        if (mn == 1000009) u--;
      }
    }
    if (p == 0) {
      printf("0\n");
      continue;
    }
    printf("%d\n", u);
    for (int i = 0; i < u; i++) {
      printf("%d %d %d\n", P[i].a, P[i].b, P[i].liu);
    }
  }
  return 0;
}
