#include <bits/stdc++.h>
using namespace std;
int n, p, out[1010];
struct node {
  int v, c;
};
vector<node> e[1010];
int t1[1010], t2[1010], r[1010], k;
void dfs(int i, int fa, int mi) {
  if (e[i].size() == 0) {
    t1[k] = fa;
    t2[k] = i;
    r[k] = mi;
    k++;
    return;
  }
  mi = min(e[i][0].c, mi);
  dfs(e[i][0].v, fa, mi);
}
int main() {
  while (cin >> n >> p) {
    int u;
    node a;
    memset(out, 0, sizeof(out));
    for (int i = 0; i <= n; i++) e[i].clear();
    for (int i = 0; i < p; i++) {
      scanf("%d%d%d", &u, &a.v, &a.c);
      e[u].push_back(a);
      out[u]++;
      out[a.v]--;
    }
    k = 0;
    for (int i = 1; i <= n; i++)
      if (out[i] == 1) dfs(i, i, 99999999);
    printf("%d\n", k);
    for (int i = 0; i < k; i++) printf("%d %d %d\n", t1[i], t2[i], r[i]);
  }
}
