#include <bits/stdc++.h>
using namespace std;
const int max1 = 1e7 + 5;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long t = 1;
  while (t--) {
    map<int, int> in, out, len;
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
      int a, b, d;
      cin >> a >> b >> d;
      in[b] = a;
      out[a] = b;
      if (len[a] == 0)
        len[a] = d;
      else
        len[a] = min(len[a], d);
      if (len[b] == 0)
        len[b] = d;
      else
        len[b] = min(len[b], d);
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
      if (in[i] == 0 && out[i] != 0) {
        ans++;
      }
    }
    cout << ans << "\n";
    for (int i = 1; i <= n; i++) {
      if (in[i] == 0 && out[i] != 0) {
        int dist = len[i];
        int j = out[i];
        while (out[j] != 0) {
          dist = min(len[j], dist);
          j = out[j];
        }
        dist = min(len[j], dist);
        cout << i << " " << j << " " << dist << "\n";
      }
    }
  }
}
