#include <bits/stdc++.h>
using namespace std;
int diameter[1005], parent[1005], t;
bool in_deg[1005], out_deg[1005];
int n, m;
bool visited[1005];
int find(int i, int org) {
  if (parent[i] == i) return i;
  if (parent[i] == org) return -1;
  int result = find(parent[i], org);
  parent[i] = result;
  return result;
}
void unionize(int i, int j) {
  parent[i] = j;
  find(i, i);
}
int main() {
  cin >> n >> m;
  int u, v, w;
  fill_n(diameter, n + 1, 10000000);
  for (int i = 1; i <= n; ++i) parent[i] = i;
  int mm = m;
  while (mm--) {
    cin >> u >> v >> w;
    diameter[u] = w;
    out_deg[u] = true;
    in_deg[v] = true;
    unionize(u, v);
  }
  int t = 0;
  for (int i = 1, par; i <= n; ++i) {
    if (!in_deg[i] && out_deg[i]) {
      ++t;
    }
    par = find(i, i);
    if (par == -1) continue;
    diameter[par] = min(diameter[i], diameter[par]);
  }
  cout << t << '\n';
  for (int i = 1; i <= n; ++i) {
    if (!in_deg[i] && out_deg[i]) {
      int fin = find(i, i);
      cout << i << ' ' << fin << ' ' << diameter[fin] << '\n';
    }
  }
}
