#include <bits/stdc++.h>
using namespace std;
struct Node {
  int s, e, d;
};
int a[1010];
int in[1010];
int out[1010];
int vis[1010];
int d[1010][1010];
int n, p;
int cnt = 0;
int ans;
Node node[1010];
void dfs(int x) {
  if (!out[x]) {
    node[cnt].e = x;
    node[cnt].d = ans;
    return;
  } else {
    ans = min(ans, d[x][a[x]]);
    dfs(a[x]);
  }
}
int cmp(Node a, Node b) { return a.s < b.s; }
int main() {
  scanf("%d %d", &n, &p);
  cnt = 0;
  for (int i = 0; i < p; i++) {
    int ta, tb, tc;
    scanf("%d %d %d", &ta, &tb, &tc);
    a[ta] = tb;
    out[ta]++;
    in[tb]++;
    d[ta][tb] = tc;
    vis[ta] = vis[tb] = 1;
  }
  for (int i = 1; i <= n && p != 0; i++) {
    if (in[i] == 0 && vis[i]) {
      ans = 1 << 30;
      node[cnt].s = i;
      dfs(i);
      cnt++;
    }
  }
  sort(node, node + cnt, cmp);
  printf("%d\n", cnt);
  for (int i = 0; i < cnt; i++) {
    printf("%d %d %d\n", node[i].s, node[i].e, node[i].d);
  }
}
