#include <bits/stdc++.h>
using namespace std;
long long n, q, par[1000005], child[1000005], dp[1000005], val[1005][1005];
vector<long long> e[1000005], v;
vector<pair<pair<long long, long long>, long long> > ans;
bool mark[1000005];
void dfs(int u, int p) {
  mark[u] = 1;
  v.push_back(u);
  if (p == -1)
    dp[u] = 1e18;
  else
    dp[u] = min(dp[p], val[p][u]);
  for (int x : e[u]) {
    if (mark[x]) continue;
    dfs(x, u);
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> q;
  for (int i = 0; i < q; i++) {
    long long x, y, w;
    cin >> x >> y >> w;
    val[x][y] = w;
    par[y]++;
    child[x]++;
    e[x].push_back(y);
  }
  for (int i = 1; i <= n; i++) {
    if (par[i] == 0) {
      v.clear();
      dfs(i, -1);
      for (int j = 1; j < v.size(); j++)
        if (child[v[j]] == 0) ans.push_back({{i, v[j]}, dp[v[j]]});
    }
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << '\n';
  for (pair<pair<long long, long long>, long long> u : ans)
    cout << u.first.first << ' ' << u.first.second << ' ' << u.second << '\n';
  return 0;
}
