#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > g[1001];
bool noInicio[1001];
pair<int, int> dfs(int u, int d) {
  if (!g[u].size()) return make_pair(u, d);
  return dfs(g[u][0].first, min(d, g[u][0].second));
}
int main() {
  int n, q;
  cin >> n >> q;
  for (int i = 0; i < q; i++) {
    int u, v, d;
    cin >> u >> v >> d;
    noInicio[v] = true;
    g[u].push_back(make_pair(v, d));
  }
  vector<pair<int, pair<int, int> > > ans;
  for (int i = 1; i <= n; i++) {
    if (!noInicio[i] and g[i].size())
      ans.push_back(make_pair(i, dfs(i, 1 << 30)));
  }
  cout << ans.size() << endl;
  for (auto p : ans) {
    cout << p.first << " " << p.second.first << " " << p.second.second << endl;
  }
  return 0;
}
