#include <bits/stdc++.h>
using namespace std;
const long long int N = 1005;
long long int n, p;
long long int indeg[N], outdeg[N], nxt[N], diam[N];
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  cin >> n >> p;
  for (long long int i = 1; i <= p; i++) {
    long long int u, v, w;
    cin >> u >> v >> w;
    indeg[v]++;
    outdeg[u]++;
    nxt[u] = v;
    diam[u] = w;
  }
  long long int ans = 0;
  for (long long int i = 1; i <= n; i++)
    ans += (outdeg[i] > 0 && indeg[i] == 0);
  cout << ans << "\n";
  for (long long int i = 1; i <= n; i++) {
    if (outdeg[i] > 0 && indeg[i] == 0) {
      long long int index = i, val = 1e9;
      while (outdeg[index]) {
        val = min(val, diam[index]);
        index = nxt[index];
      }
      cout << i << " " << index << " " << val << "\n";
    }
  }
  return 0;
}
