#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, p, i, j, ai, bi, d;
  cin >> n >> p;
  int *a = new int[1010];
  memset(a, 0, 1010 * 4);
  int *ish = new int[1010];
  memset(ish, 0, 1010 * 4);
  int *dish = new int[1010];
  memset(dish, 0, 1010 * 4);
  for (i = 0; i < p; ++i) {
    cin >> ai >> bi >> d;
    ish[ai] = bi;
    dish[ai] = d;
    a[bi] = 1;
  }
  int all = 0;
  for (i = 0; i < n; ++i) {
    if (a[i + 1] == 0 && ish[i + 1] != 0) all++;
  }
  cout << all << endl;
  for (i = 0; i < n; ++i) {
    if (a[i + 1] == 0 && ish[i + 1] != 0) {
      int dmin = 1000002;
      int last = i + 1;
      while (ish[last] != 0) {
        if (dish[last] < dmin) dmin = dish[last];
        last = ish[last];
      }
      cout << i + 1 << " " << last << " " << dmin << endl;
    }
  }
  cin >> i;
  return 0;
}
