#include <bits/stdc++.h>
using namespace std;
int num_entradas[1111], sig[1111], val[1111], num_salidas[1111];
int ans;
int last_node;
void dfs(int nodo) {
  if (sig[nodo] != 0) {
    ans = min(ans, val[nodo]);
    dfs(sig[nodo]);
  } else
    last_node = nodo;
}
int main() {
  int n, m, x, y, z;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    cin >> x >> y >> z;
    num_entradas[y]++;
    num_salidas[x]++;
    sig[x] = y;
    val[x] = z;
  }
  int cont = 0;
  for (int i = 1; i <= n; i++)
    if (num_entradas[i] == 0 && num_salidas[i] != 0) cont++;
  cout << cont << endl;
  for (int i = 1; i <= n; i++) {
    if (num_entradas[i] == 0 && num_salidas[i] != 0) {
      ans = (1 << 30);
      dfs(i);
      cout << i << " " << last_node << " " << ans << endl;
    }
  }
  return 0;
}
