#include <bits/stdc++.h>
using namespace std;
int p[1005][1005], Min, l, t, u, c[1005], r[1005], f[1005], n;
struct {
  int s, e, v;
} h[1005];
void d(int x) {
  int i;
  if (t || u) return;
  if (f[x] && c[x] && r[x]) t = 1;
  f[x] = 1;
  if (!c[x] && h[l].s != x) {
    h[l].e = x;
    h[l++].v = Min;
    u = 1;
    return;
  }
  for (i = 1; i <= n; i++)
    if (p[x][i]) {
      if (Min > p[x][i]) Min = p[x][i];
      d(i);
    }
}
int main() {
  int m, i, x, y, v;
  scanf("%d%d", &n, &m);
  if (n == 0 || m == 0) {
    printf("0\n");
    return 0;
  }
  memset(c, 0, sizeof(c));
  memset(r, 0, sizeof(r));
  memset(p, 0, sizeof(p));
  for (i = 0; i < m; i++) {
    scanf("%d%d%d", &x, &y, &v);
    c[x] = 1;
    r[y] = 1;
    p[x][y] = v;
  }
  l = 0;
  for (i = 1; i <= n; i++)
    if (!r[i]) {
      h[l].s = i;
      t = u = 0;
      memset(f, 0, sizeof(f));
      Min = 999999;
      d(i);
      if (t) break;
    }
  if (t)
    printf("0\n");
  else {
    printf("%d\n", l);
    for (i = 0; i < l; i++) printf("%d %d %d\n", h[i].s, h[i].e, h[i].v);
  }
  return 0;
}
