#include <bits/stdc++.h>
using namespace std;
const int INF = 0x7fffffff;
int N, P;
int incoming[1001], outgoing[1001];
int outcap[1001];
int aa[1001], ab[1001], ad[1001], an;
int main() {
  cin >> N >> P;
  for (int i = int(1); i < int(N + 1); ++i) {
    incoming[i] = outgoing[i] = -1;
  }
  for (int i = int(0); i < int(P); ++i) {
    int a, b, d;
    cin >> a >> b >> d;
    outgoing[a] = b;
    incoming[b] = a;
    outcap[a] = d;
  }
  an = 0;
  for (int i = int(1); i < int(N + 1); ++i) {
    if (outgoing[i] != -1 && incoming[i] == -1) {
      int a = i;
      int cap = INF;
      while (outgoing[a] != -1) {
        cap = min(cap, outcap[a]);
        a = outgoing[a];
      }
      aa[an] = i;
      ab[an] = a;
      ad[an] = cap;
      ++an;
    }
  }
  printf("%d\n", an);
  for (int i = int(0); i < int(an); ++i)
    printf("%d %d %d\n", aa[i], ab[i], ad[i]);
  return 0;
}
