#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[1005];
int b[1005];
int d[1005];
int last = 0;
int mi = 10000000;
void dfs(int v) {
  if (a[v])
    dfs(a[v]);
  else
    last = v;
  mi = min(mi, d[v]);
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++) d[i] = 100000000;
  for (int i = 0; i < m; i++) {
    int x, y, z;
    cin >> x >> y >> z;
    a[x] = y;
    b[y] = x;
    d[x] = z;
  }
  vector<pair<pair<int, int>, int> > ans;
  for (int i = 1; i <= n; i++) {
    if (b[i] == 0) {
      mi = 100000000;
      last = i;
      dfs(i);
      if (last != i) ans.push_back(make_pair(make_pair(i, last), mi));
    }
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++) {
    cout << ans[i].first.first << " " << ans[i].first.second << " "
         << ans[i].second << endl;
  }
  return 0;
}
