#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, p;
  scanf("%d %d", &n, &p);
  int i;
  int child[1001][2], deg[1001] = {0};
  memset(child, 0, sizeof child);
  for (i = 0; i < p; i++) {
    int a, b, d;
    scanf("%d %d %d", &a, &b, &d);
    child[a][0] = b;
    child[a][1] = d;
    deg[a]++;
    deg[b]--;
  }
  vector<int> v[3];
  for (i = 1; i <= n; i++) {
    if (deg[i] == 1) {
      int mini = 1e+8;
      v[0].push_back(i);
      int node = i, prev;
      while (node) {
        if (child[node][1] != 0)
          mini = mini > child[node][1] ? child[node][1] : mini;
        prev = node;
        node = child[node][0];
      }
      v[1].push_back(prev);
      v[2].push_back(mini);
    }
  }
  printf("%d\n", v[0].size());
  vector<int>::iterator a, b, c;
  for (a = v[0].begin(), b = v[1].begin(), c = v[2].begin(); a < v[0].end();
       a++, b++, c++) {
    printf("%d %d %d\n", *a, *b, *c);
  }
  return 0;
}
