#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  pair<int, int> from[1001] = {}, to[1001] = {};
  for (int i = 0; i < m; i++) {
    int a, b, d;
    cin >> a >> b >> d;
    from[b] = pair<int, int>(a, d);
    to[a] = pair<int, int>(b, d);
  }
  vector<pair<pair<int, int>, int> > ans;
  for (int i = 1; i <= n; i++) {
    if (from[i].first) continue;
    int x = i, tmp = 12345678;
    while (to[x].first) {
      tmp = min(tmp, to[x].second);
      x = to[x].first;
    }
    if (i != x) ans.push_back(pair<pair<int, int>, int>({i, x}, tmp));
  }
  cout << ans.size() << endl;
  for (auto i : ans)
    cout << i.first.first << ' ' << i.first.second << ' ' << i.second << endl;
  return 0;
}
