#include <bits/stdc++.h>
using namespace std;
bitset<1002> start;
bitset<1002> nstart;
int main() {
  long long v, x, y, e, a, b, w, in = 0, inicios;
  pair<long long, long long> h;
  cin >> v >> e;
  map<int, pair<int, int> > mp;
  for (int i = 0; i < e; i++) {
    cin >> x >> y >> w;
    if (!nstart[x]) start.set(x);
    start.set(y, false);
    nstart.set(y);
    mp[x] = make_pair(y, w);
  }
  cout << start.count() << '\n';
  for (int i = 1; i <= v; i++) {
    if (!start[i]) continue;
    int j = i;
    int minn = 1000001;
    while (mp.find(j) != mp.end()) {
      minn = min(minn, mp[j].second);
      j = mp[j].first;
    }
    cout << i << ' ' << j << ' ' << minn << '\n';
  }
  return 0;
}
