#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> g[1005];
int n, m, x, y, d, di[1005];
int first, last, af;
vector<pair<pair<int, int>, int>> ans;
bool ok, uz[1005];
void dfs(int k) {
  last = k;
  if (!ok) return;
  for (auto x : g[k]) {
    if (uz[x.first]) {
      ok = false;
      return;
    }
    af = min(af, x.second);
    dfs(x.first);
  }
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= m; ++i) {
    cin >> x >> y >> d;
    ++di[y];
    g[x].push_back(make_pair(y, d));
  }
  for (int i = 1; i <= n; ++i) {
    if (di[i]) continue;
    first = i;
    af = 999999999;
    ok = true;
    memset(uz, 0, sizeof(uz));
    dfs(i);
    if (last != first && ok)
      ans.push_back(make_pair(make_pair(first, last), af));
  }
  cout << ans.size() << '\n';
  for (auto x : ans)
    cout << x.first.first << ' ' << x.first.second << ' ' << x.second << '\n';
  return 0;
}
