#include <bits/stdc++.h>
using namespace std;
struct node {
  int v, next;
  int val;
};
node edge[1005];
int n, p;
int ind[1005], oud[1005];
int cnt;
int head[1005];
void addedge(int u, int v, int val) {
  edge[cnt].v = v;
  edge[cnt].val = val;
  edge[cnt].next = head[u];
  head[u] = cnt++;
}
struct ansnode {
  int u, v, val;
};
ansnode ans[1005];
int num;
void addans(int u, int v, int val) {
  ans[num].u = u;
  ans[num].v = v;
  ans[num].val = val;
  num++;
}
bool cmp(ansnode t1, ansnode t2) { return t1.u < t2.u; }
int main() {
  while (scanf("%d%d", &n, &p) != EOF) {
    memset(ind, 0, sizeof(ind));
    memset(oud, 0, sizeof(oud));
    cnt = 0;
    memset(head, -1, sizeof(head));
    for (int i = 0; i < p; i++) {
      int u, v, val;
      scanf("%d%d%d", &u, &v, &val);
      addedge(u, v, val);
      ind[v]++;
      oud[u]++;
    }
    int res;
    res = 0;
    num = 0;
    for (int i = 1; i <= n; i++)
      if (ind[i] == 0) {
        if (oud[i] == 0) {
          continue;
        }
        res++;
        int v, val;
        val = 0x3f3f3f3f;
        int j = head[i];
        while (j != -1) {
          v = edge[j].v;
          val = min(val, edge[j].val);
          j = head[edge[j].v];
        }
        addans(i, v, val);
      }
    sort(ans, ans + res, cmp);
    printf("%d\n", res);
    for (int i = 0; i < res; i++) {
      printf("%d %d %d\n", ans[i].u, ans[i].v, ans[i].val);
    }
  }
  return 0;
}
