#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, p;
  int a[1000], b[1000], d[1000];
  bool use[1001];
  int ans[1000][3];
  int t;
  cin >> n >> p;
  for (int i = 0; i < p; i++) cin >> a[i] >> b[i] >> d[i];
  for (int i = 1; i <= n; i++) use[i] = true;
  for (int i = 0; i < p; i++) use[b[i]] = false;
  t = 0;
  for (int i = 1; i <= n; i++) {
    if (use[i]) {
      int to = i;
      int min = 100000000;
      while (1) {
        int j;
        for (j = 0; j < p; j++) {
          if (to == a[j]) {
            to = b[j];
            if (min > d[j]) min = d[j];
            break;
          }
        }
        if (to == i || j == p) break;
      }
      if (to != i) {
        ans[t][0] = i;
        ans[t][1] = to;
        ans[t][2] = min;
        t++;
      }
    }
  }
  for (int i = 0; i < t; i++) {
    for (int j = i + 1; j < t; j++) {
      if (ans[i][0] > ans[j][0]) {
        swap(ans[i][0], ans[j][0]);
        swap(ans[i][1], ans[j][1]);
        swap(ans[i][2], ans[j][2]);
      }
    }
  }
  cout << t << endl;
  for (int i = 0; i < t; i++) {
    cout << ans[i][0] << " " << ans[i][1] << " " << ans[i][2] << endl;
  }
}
