#include <bits/stdc++.h>
using namespace std;
long n, k, a, b, c, deg[20000], temp;
vector<long> ans1, ans2, ans3;
vector<pair<long, long> > g[20000];
long lst;
long dfs(long v) {
  lst = v;
  if (g[v].size() == 0) return 1e9;
  return min(g[v][0].second, dfs(g[v][0].first));
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n >> k;
  for (int i = 1; i <= k; i++) {
    cin >> a >> b >> c;
    g[a].push_back(make_pair(b, c));
    deg[b]++;
  }
  for (int i = 1; i <= n; i++) {
    if (deg[i]) continue;
    if (g[i].size() == 0) continue;
    temp = dfs(i);
    ans1.push_back(i);
    ans2.push_back(lst);
    ans3.push_back(temp);
  }
  cout << ans1.size() << endl;
  for (int i = 0; i < ans1.size(); i++) {
    cout << ans1[i] << " " << ans2[i] << " " << ans3[i] << endl;
  }
  cin.get();
  cin.get();
  return 0;
}
