#include <bits/stdc++.h>
using namespace std;
struct node {
  int u;
  int v;
  int d;
} ans[1005];
int t;
int w[1005][1005], vis[1005], in[1005];
vector<int> e[1005];
int dfs(int x, int d) {
  if (vis[x]) return 0;
  vis[x] = 1;
  if (e[x].size() == 0) {
    ans[t].v = x;
    ans[t].d = d;
    return 1;
  }
  if (dfs(e[x][0], min(d, w[x][e[x][0]]))) return 1;
  return 0;
}
bool cmp(node a, node b) { return a.u < b.u; }
int main() {
  int n, m;
  while (~scanf("%d%d", &n, &m)) {
    for (int i = 1; i <= n; i++) e[i].clear();
    t = 0;
    memset(vis, 0, sizeof(vis));
    memset(in, 0, sizeof(in));
    for (int i = 1; i <= m; i++) {
      int x, y, z;
      scanf("%d%d%d", &x, &y, &z);
      e[x].push_back(y);
      in[y]++;
      w[x][y] = z;
    }
    for (int i = 1; i <= n; i++)
      if (!vis[i] && in[i] == 0) {
        ans[t].u = i;
        int flag = dfs(i, 10000000);
        if (flag) t++;
        if (t != 0 && ans[t - 1].u == ans[t - 1].v) t--;
      }
    sort(ans, ans + t, cmp);
    printf("%d\n", t);
    for (int i = 0; i < t; i++)
      printf("%d %d %d\n", ans[i].u, ans[i].v, ans[i].d);
  }
  return 0;
}
