#include <bits/stdc++.h>
using namespace std;
struct answer {
  int f, t, x;
  answer(int _f, int _t, int _x) { f = _f, t = _t, x = _x; }
};
vector<pair<int, int> > v;
vector<bool> g;
vector<answer> ans;
int n, m, f, t, x, mine, last;
void dfs(int u) {
  while (v[u].first >= 0) mine = min(mine, v[u].second), u = v[u].first;
  last = u;
}
int main() {
  cin >> n >> m;
  v.assign(n, make_pair(-1, 1000000));
  g.assign(n, false);
  for (int i = 0; i < m; i++) {
    cin >> f >> t >> x;
    v[f - 1] = make_pair(t - 1, x);
    g[t - 1] = true;
  }
  for (int i = 0; i < n; i++)
    if (!g[i] && v[i].first != -1) {
      mine = 1000000;
      dfs(i);
      ans.push_back(answer(i + 1, last + 1, mine));
    }
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++)
    cout << ans[i].f << ' ' << ans[i].t << ' ' << ans[i].x << endl;
  return 0;
}
