#include <bits/stdc++.h>
using namespace std;
int dx[] = {-1, 1, 0, 0, 0, 0, 0, 0};
int dy[] = {0, 0, 1, -1, 0, 0, 0, 0};
int dz[] = {0, 0, 0, 0, 1, -1, 0, 0};
const int inf = 10000000;
int main() {
  int n, p;
  cin >> n >> p;
  int in[n], out[n];
  memset(in, 0, sizeof(in));
  memset(out, 0, sizeof(out));
  map<int, pair<int, int> > a;
  if (p == 0) {
    cout << 0 << endl;
    return 0;
  }
  for (int i = 0; i < p; i++) {
    int t1, t2, t3;
    cin >> t1 >> t2 >> t3;
    t1--;
    t2--;
    a[t1] = pair<int, int>(t2, t3);
    out[t1] = 1;
    in[t2] = 1;
  }
  int ans = 0;
  for (int i = 0; i < n; i++) {
    if (in[i] == 0 && out[i] != 0) ans++;
  }
  cout << ans << endl;
  ;
  if (!ans) return 0;
  for (int i = 0; i < n; i++) {
    if (in[i] == 1) continue;
    int mind = 100000000;
    int j = i;
    while (out[j] != 0) {
      map<int, pair<int, int> >::iterator it = a.find(j);
      j = (*it).second.first;
      mind = min(mind, (*it).second.second);
    }
    if (i != j) cout << (i + 1) << " " << j + 1 << " " << mind << endl;
  }
  return 0;
}
