#include <bits/stdc++.h>
using namespace std;
int nilai[1005], degin[1005], degout[1005], n, p, nxt[1005];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> p;
  for (int i = 0; i < p; ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    degout[a]++;
    degin[b]++;
    nilai[a] = c;
    nxt[a] = b;
  }
  int ans = 0;
  for (int i = 1; i <= n; ++i) {
    if (!degin[i] && degout[i]) ans++;
  }
  cout << ans << '\n';
  for (int i = 1; i <= n; ++i) {
    int cur = i, mins = INT_MAX;
    if (degin[cur] || !degout[cur]) continue;
    while (degout[cur]) {
      mins = min(mins, nilai[cur]);
      cur = nxt[cur];
    }
    cout << i << ' ' << cur << ' ' << mins << '\n';
  }
}
