#include <bits/stdc++.h>
using namespace std;
int child[1005], weight[1005], indegree[1005], outdegree[1005];
int dia[1005], tank[1005], tap[1005];
int main() {
  int n, p, count, i, mn, a, b, d, parent;
  scanf("%d %d", &n, &p);
  if (p == 0) {
    printf("0\n");
    return 0;
  }
  for (i = 0; i < p; i++) {
    scanf("%d %d %d", &a, &b, &d);
    child[a] = b;
    weight[a] = d;
    indegree[b] = 1;
    outdegree[a] = 1;
  }
  count = 0;
  for (i = 1; i <= n; i++) {
    if ((indegree[i] == 0) && (outdegree[i] != 0)) {
      tank[count] = i;
      parent = i;
      mn = 10000000;
      while (1) {
        if (outdegree[parent] == 0) break;
        mn = min(weight[parent], mn);
        parent = child[parent];
      }
      tap[count] = parent;
      dia[count] = mn;
      count++;
    }
  }
  printf("%d\n", count);
  for (i = 0; i < count; i++) {
    printf("%d %d %d\n", tank[i], tap[i], dia[i]);
  }
  return 0;
}
