#include <bits/stdc++.h>
using namespace std;
int N, P;
int IN[2000], OUT[2000], DIA[2000];
int A, B, D;
int main() {
  cin >> N >> P;
  while (P--) {
    cin >> A >> B >> D;
    IN[B] = A;
    OUT[A] = B;
    DIA[A] = D;
  }
  int z = 0;
  for (int i = 1; i <= N; i++)
    if (IN[i] == 0 && OUT[i] != 0) z++;
  cout << z << endl;
  for (int i = 1; i <= N; i++)
    if (IN[i] == 0 && OUT[i] != 0) {
      int x = i;
      int d = DIA[x];
      while (OUT[x] != 0) {
        d = min(DIA[x], d);
        x = OUT[x];
      }
      cout << i << " " << x << " " << d << endl;
    }
  return 0;
}
