#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cout << fixed;
  cout.precision(10);
  int n, m;
  cin >> n >> m;
  vector<int> in(n + 1), out(n + 1);
  vector<int> p(n + 1), d(n + 1);
  for (int i = 0; i < m; i++) {
    int a, b, w;
    cin >> a >> b >> w;
    in[b]++;
    out[a]++;
    p[a] = b;
    d[a] = w;
  }
  int cnt = 0;
  for (int i = 1; i <= n; i++) {
    if (out[i] == 1 and in[i] == 0) {
      cnt++;
    }
  }
  cout << cnt << "\n";
  for (int i = 1; i <= n; i++) {
    if (out[i] == 1 and in[i] == 0) {
      int mn = INT_MAX;
      int x = i;
      while (p[x] != 0) {
        mn = min(mn, d[x]);
        x = p[x];
      }
      cout << i << " " << x << " " << mn << "\n";
    }
  }
  return 0;
}
