#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > a;
vector<int> b;
int main() {
  int n, p, u, v, d, h, i, count = 0;
  cin >> n >> p;
  a.resize(n, make_pair(-1, -1));
  b.resize(n, -1);
  for (int i = 0; i < p; i++) {
    cin >> u >> v >> d;
    a[u - 1] = make_pair(v - 1, d);
    b[v - 1] = u - 1;
  }
  for (i = 0; i < n; i++)
    if (b[i] == -1 && a[i].first >= 0) count++;
  cout << count << endl;
  for (i = 0; i < n; i++) {
    if (b[i] == -1 && a[i].first >= 0) {
      h = a[i].first;
      d = a[i].second;
      while (a[h].first != -1) {
        d = min(d, a[h].second);
        h = a[h].first;
      }
      cout << i + 1 << " " << h + 1 << " " << d << endl;
    }
  }
  return 0;
}
