#include <bits/stdc++.h>
using namespace std;
bool in[1001], out[1001];
bool vis[1001];
int Min;
int last;
vector<vector<pair<int, int> > > adj(1001);
void dfs(int i) {
  vis[i] = 1;
  if (adj[i].empty()) last = i;
  for (int j = 0; j < adj[i].size(); j++) {
    Min = min(Min, adj[i][j].second);
    dfs(adj[i][j].first);
  }
}
int main() {
  int n, p;
  cin >> n >> p;
  for (int i = 0; i < p; i++) {
    int x, y, z;
    cin >> x >> y >> z;
    in[y] = 1;
    out[x] = 1;
    adj[x].push_back({y, z});
  }
  vector<pair<int, pair<int, int> > > ans;
  for (int i = 1; i <= n; i++) {
    if (out[i] && !in[i]) {
      Min = 1e9;
      last = -1;
      dfs(i);
      ans.push_back({i, {last, Min}});
    }
  }
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++)
    cout << ans[i].first << " " << ans[i].second.first << " "
         << ans[i].second.second << endl;
  return 0;
}
