#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1E-15;
const int inf = int(1e9) + 7;
const int maxN = 1000 + 5;
int in[maxN], to[maxN], cs[maxN];
int n, m;
int main() {
  scanf("%d%d", &n, &m);
  int a, b, c;
  for (int(i) = 0; (i) < (m); ++(i)) {
    scanf("%d%d%d", &a, &b, &c);
    to[a] = b;
    in[b] = 1;
    cs[a] = c;
  }
  int tot = 0;
  for (int(i) = (1); (i) < (n + 1); ++(i))
    if (in[i] == 0 && to[i] != 0) tot++;
  printf("%d\n", tot);
  for (int(i) = (1); (i) < (n + 1); ++(i))
    if (in[i] == 0 && to[i] != 0) {
      int x = i, ans = inf;
      while (to[x]) {
        ans = min(ans, cs[x]);
        x = to[x];
      }
      printf("%d %d %d\n", i, x, ans);
    }
  return 0;
}
