#include <bits/stdc++.h>
using namespace std;
int n, p, a[1010][4], i, j, c[1010][4], num = 0;
;
bool b[1010];
int main() {
  scanf("%d%d", &n, &p);
  memset(a, 0, sizeof(a));
  memset(b, 0, sizeof(b));
  memset(c, 0, sizeof(c));
  for (i = 1; i <= p; i++) {
    int x, y, z;
    scanf("%d%d%d", &x, &y, &z);
    a[x][0] = y;
    a[x][1] = z;
    a[y][3] = x;
  }
  for (i = 1; i <= n; i++) {
    if (a[i][3] == 0 && a[i][0] != 0) {
      int min = a[i][1];
      j = i;
      while (a[j][0] != 0) {
        if (min > a[j][1]) min = a[j][1];
        j = a[j][0];
      }
      c[i][0] = j;
      c[i][1] = min;
      num++;
    }
  }
  printf("%d\n", num);
  for (i = 1; i <= n; i++) {
    if (c[i][0] != 0) {
      printf("%d %d %d\n", i, c[i][0], c[i][1]);
    }
  }
  return 0;
}
