#include <bits/stdc++.h>
using namespace std;
int f[1005][1005], in[1005], out[1005];
struct node {
  int a, b, c, f;
} q[1005];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  memset(f, 0, sizeof(f));
  memset(in, 0, sizeof(in));
  memset(out, 0, sizeof(out));
  for (int i = 0; i < m; i++) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    f[a][b] = c;
    in[b]++;
    out[a]++;
  }
  int nq = 0;
  for (int i = 1; i <= n; i++) {
    if (!in[i]) {
      int ans = 1 << 30;
      int now = i;
      while (out[now]) {
        for (int j = 1; j <= n; j++)
          if (f[now][j]) {
            ans = min(ans, f[now][j]);
            now = j;
            break;
          }
        if (now == i) break;
      }
      if (now != i) {
        q[nq].a = i;
        q[nq].b = now;
        q[nq].c = ans;
        nq++;
      }
    }
  }
  printf("%d\n", nq);
  for (int i = 0; i < nq; i++) {
    printf("%d %d %d\n", q[i].a, q[i].b, q[i].c);
  }
}
