#include <bits/stdc++.h>
using namespace std;
int a[100001], cap[100001], b[100001];
int dfs(int i) {
  if (a[i] == -1) return i;
  int ret = dfs(a[i]);
  return ret;
}
int ff(int i) {
  int tmp = 1000000;
  while (a[i] != -1) {
    tmp = min(tmp, cap[i]);
    i = a[i];
  }
  return tmp;
}
int main() {
  int n, p;
  scanf("%d%d", &n, &p);
  memset(a, -1, sizeof(a));
  memset(b, -1, sizeof(b));
  for (int i = 0; i < p; i++) {
    int x, y, z;
    scanf("%d %d %d", &x, &y, &z);
    a[x - 1] = y - 1;
    b[y - 1] = x - 1;
    cap[x - 1] = z - 1;
  }
  vector<int> vec;
  for (int i = 0; i < n; i++) {
    if (b[i] == -1 && a[i] != -1) vec.push_back(i);
  }
  printf("%d\n", vec.size());
  sort(vec.begin(), vec.end());
  for (int i = 0; i < vec.size(); i++) {
    int sink = dfs(vec[i]);
    int dia = ff(vec[i]);
    printf("%d %d %d\n", vec[i] + 1, sink + 1, dia + 1);
  }
  scanf(" ");
  return 0;
}
