#include <bits/stdc++.h>
int house[1002][3], done[1002], ans[1002][3];
int main() {
  int next, n, p, min = 1000000, i, j, inter[1000][3], tank, tap, dia,
                  count = 0;
  scanf("%d%d", &n, &p);
  for (i = 0; i < p; i++) {
    scanf("%d%d%d", &inter[i][0], &inter[i][1], &inter[i][2]);
    house[inter[i][0]][0] = inter[i][1];
    house[inter[i][1]][1] = inter[i][0];
    house[inter[i][0]][2] = inter[i][2];
  }
  if (p == 0) {
    printf("0\n");
    return 0;
  }
  for (i = 1; i <= n; i++) {
    if (done[i] || (house[i][0] == 0 && house[i][1] == 0)) continue;
    if (house[i][1] == 0) {
      min = house[i][2];
      tank = i;
      next = house[i][0];
      done[i] = 1;
      while (house[next][0] != 0) {
        if (done[next]) break;
        if (house[next][2] < min) min = house[next][2];
        done[next] = 1;
        next = house[next][0];
      }
      if (done[next]) continue;
      count++;
      ans[count][0] = tank;
      ans[count][1] = next;
      ans[count][2] = min;
    }
  }
  printf("%d\n", count);
  for (i = 1; i <= count; i++)
    printf("%d %d %d\n", ans[i][0], ans[i][1], ans[i][2]);
  return 0;
}
