#include <bits/stdc++.h>
using namespace std;
struct T {
  int a, b, c;
} ans[2222];
int a, b, c, x[2222], y[2222], p[2222], n, m, e[2222], s, w[2222], kol = 0;
bool f[2222];
void dfs(int k) {
  f[k] = 1;
  if (x[k] == 0) s = k;
  for (int q = x[k]; q; q = p[q])
    if (!f[y[q]]) {
      m = ((m) < (w[q]) ? (m) : (w[q]));
      dfs(y[q]);
    }
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    scanf("%d%d%d", &a, &b, &c);
    y[i] = b, p[i] = x[a], x[a] = i, w[i] = c;
    ++e[b];
  }
  for (int i = 1; i <= n; i++)
    if (!e[i]) {
      m = INT_MAX;
      dfs(i);
      if (i == s) continue;
      ans[kol++] = (T){i, s, m};
    }
  printf("%d\n", kol);
  for (int i = 0; i < kol; i++)
    printf("%d %d %d\n", ans[i].a, ans[i].b, ans[i].c);
  return 0;
}
