#include <bits/stdc++.h>
int a[1005][1005];
int in[1005], out[1005];
int n, num, root;
char vis[1005];
struct node {
  int u, v, c;
} edge[1000005];
void dfs(int u, int ans) {
  int i;
  vis[u] = 1;
  if (out[u] == 0 && u != root) {
    edge[num].u = root;
    edge[num].v = u;
    edge[num].c = ans;
    num++;
    return;
  }
  for (i = 1; i <= n; i++)
    if (!vis[i] && a[u][i]) {
      if (ans > a[u][i])
        dfs(i, a[u][i]);
      else
        dfs(i, ans);
    }
}
int main() {
  int m, i, u, v, c;
  while (scanf("%d%d", &n, &m) != EOF) {
    if (n == 1 || m == 0) {
      printf("0\n");
      continue;
    }
    memset(a, 0, sizeof(a));
    memset(in, 0, sizeof(in));
    memset(out, 0, sizeof(out));
    num = 0;
    for (i = 0; i < m; i++) {
      scanf("%d%d%d", &u, &v, &c);
      a[u][v] = c;
      in[v]++;
      out[u]++;
    }
    for (i = 1; i <= n; i++)
      if (in[i] == 0) {
        memset(vis, 0, sizeof(vis));
        root = i;
        dfs(i, 0x3f3f3f3f);
      }
    printf("%d\n", num);
    for (i = 0; i < num; i++)
      printf("%d %d %d\n", edge[i].u, edge[i].v, edge[i].c);
  }
  return 0;
}
