#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 5;
const long long inf = 9e18 + 9;
const int mod = 1e9 + 7;
long long res;
int indeg[N], outdeg[N], diam[N], adj[N];
void solve() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v, val;
    cin >> u >> v >> val;
    outdeg[u]++;
    indeg[v]++;
    diam[u] = val;
    adj[u] = v;
  }
  for (int i = 1; i <= n; i++) {
    if (outdeg[i] > 0 && indeg[i] == 0) {
      res++;
    }
  }
  cout << res << "\n";
  for (int i = 1; i <= n; i++) {
    if (outdeg[i] > 0 && indeg[i] == 0) {
      int ans = INT_MAX;
      int curr = i;
      while (outdeg[curr]) {
        ans = min(ans, diam[curr]);
        curr = adj[curr];
      }
      cout << i << " " << curr << " " << ans << "\n";
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long t = 1;
  for (int i = 1; i <= t; i++) {
    solve();
  }
}
