#include <bits/stdc++.h>
using namespace std;
int n, p;
int f[1111];
int ch[1111];
int ds[1111];
int last;
bool used[1111];
int dfs(int v) {
  if (!ch[v]) {
    last = v;
    return 1e7;
  } else
    return min(dfs(ch[v]), ds[v]);
}
vector<pair<int, pair<int, int> > > ans;
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 0, u, v, d; i < p; i++) {
    scanf("%d %d %d", &u, &v, &d);
    used[u] = used[v] = true;
    f[v] = u;
    ch[u] = v;
    ds[u] = d;
  }
  for (int i = 1; i <= n; i++) {
    if (!f[i] && used[i]) {
      int res = dfs(i);
      ans.push_back(make_pair(i, make_pair(last, res)));
    }
  }
  printf("%d\n", ans.size());
  for (int i = 0; i < ans.size(); i++)
    printf("%d %d %d\n", ans[i].first, ans[i].second.first,
           ans[i].second.second);
}
