#include <bits/stdc++.h>
using namespace std;
int n, p, a, b, d, odr, val;
vector<int> adj[1001];
vector<int> adjC[1001];
int visited[1001], out[1001], in[1001];
vector<int> solF;
vector<int> solT;
vector<int> solV;
void dfs(int f, int *t, int *v) {
  if (visited[f]) {
    *t = -1;
    *v = -1;
  }
  visited[f] = 1;
  if (out[f] == 0) {
    *t = f;
    return;
  } else {
    for (int i = 0; i < adj[f].size(); ++i) {
      if (*v > adjC[f][i] || *v == -1) *v = adjC[f][i];
      dfs(adj[f][i], t, v);
    }
  }
}
int main(void) {
  scanf("%d %d", &n, &p);
  for (int i = 0; i < p; ++i) {
    scanf("%d %d %d", &a, &b, &d);
    adj[a].push_back(b);
    adjC[a].push_back(d);
    out[a]++;
    in[b]++;
  }
  for (int i = 1; i <= n; ++i) {
    if (visited[i]) continue;
    if (in[i] == 0) {
      odr = -1;
      val = -1;
      dfs(i, &odr, &val);
      if (odr != -1 && odr != i) {
        solF.push_back(i);
        solT.push_back(odr);
        solV.push_back(val);
      }
    }
  }
  printf("%d\n", solF.size());
  for (int i = 0; i < solF.size(); ++i)
    printf("%d %d %d\n", solF[i], solT[i], solV[i]);
  return 0;
}
