#include <bits/stdc++.h>
using namespace std;
int N, M, D[1111], E[1111], G[1111], P[1111];
int main() {
  cin >> N >> M;
  for (int i = 0; i < M; i++) {
    int x, y, z;
    cin >> x >> y >> z;
    G[x] = y;
    P[x] = z;
    D[y]++;
    E[x]++;
  }
  int TOT = 0;
  for (int i = 1; i <= N; i++)
    if (D[i] == 0 && E[i] != 0) TOT++;
  cout << TOT << endl;
  for (int i = 1; i <= N; i++)
    if (D[i] == 0 && E[i] != 0) {
      int S = i, T = i, R = P[i];
      for (; G[T]; T = G[T]) R = min(R, P[T]);
      cout << S << " " << T << " " << R << endl;
    }
  return 0;
}
