#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  int p;
  int x;
  int y;
  int z;
  int t = 0;
  int a[1024];
  int b[1024];
  int d[1024];
  cin >> n;
  cin >> p;
  for (int i = 1; i <= p; i++) {
    cin >> x >> y >> z;
    a[y] = x;
    b[x] = y;
    d[x] = z;
  }
  for (int i = 1; i <= n; ++i) {
    if (a[i] == 0 && b[i]) {
      ++t;
    }
  }
  cout << t << endl;
  for (int i = 1; i <= n; i++) {
    if (!a[i] && b[i]) {
      x = i;
      y = d[i];
      while (b[x]) {
        y = min(y, d[x]);
        x = b[x];
      }
      cout << i << " " << x << " " << y << endl;
    }
  }
  return 0;
}
