#include <bits/stdc++.h>
using namespace std;
int n, m, ind[1009], mn = 1e9, lst = -1, out[1009];
vector<vector<pair<int, int> > > adj(1009);
bool vis[1009];
void dfs(int node) {
  vis[node] = 1;
  for (int i = 0; i < adj[node].size(); i++) {
    int child = adj[node][i].first, cost = adj[node][i].second;
    if (!vis[child]) {
      mn = min(mn, cost);
      dfs(child);
    }
  }
  if (!out[node]) lst = node;
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int x, y, w;
    cin >> x >> y >> w;
    adj[x].push_back({y, w});
    ind[y]++;
    out[x]++;
  }
  vector<pair<pair<int, int>, int> > ans;
  for (int i = 1; i <= n; i++)
    if (ind[i] == 0 && !vis[i] && out[i]) {
      mn = 1e9;
      dfs(i);
      ans.push_back({{i, lst}, mn});
    }
  cout << ans.size() << "\n";
  for (int i = 0; i < ans.size(); i++)
    cout << ans[i].first.first << " " << ans[i].first.second << " "
         << ans[i].second << "\n";
  return 0;
}
