#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 10;
const int oo = 0x7f7f7f7f;
int ecnt, in[maxn], out[maxn];
struct Edge {
  int v, w;
  Edge *next;
} e[maxn << 1], *adj[maxn];
void add_edge(int u, int v, int w) {
  e[ecnt].v = v;
  e[ecnt].w = w;
  e[ecnt].next = adj[u];
  adj[u] = &e[ecnt++];
}
int main() {
  int n, m;
  while (~scanf("%d%d", &n, &m)) {
    ecnt = 0;
    memset(adj, 0, sizeof(adj));
    memset(in, 0, sizeof(in));
    memset(out, 0, sizeof(out));
    for (int i = 0; i < m; i++) {
      int a, b, c;
      scanf("%d%d%d", &a, &b, &c);
      add_edge(a, b, c);
      in[b]++;
      out[a]++;
    }
    if (n == m || n == 1)
      printf("0\n");
    else {
      int ans = 0;
      for (int i = 1; i <= n; i++) {
        if (in[i] == 0 && out[i] != 0) ans++;
      }
      printf("%d\n", ans);
      for (int j = 1; j <= n; j++) {
        if (in[j] == 0 && out[j] != 0) {
          int mi = oo, t;
          for (Edge *p = adj[j]; p;) {
            int v = p->v;
            mi = min(mi, p->w);
            if (out[v] == 0) {
              t = v;
              break;
            }
            p = adj[v];
          }
          printf("%d %d %d\n", j, t, mi);
        }
      }
    }
  }
}
