#include <bits/stdc++.h>
using namespace std;
string::iterator it;
vector<int>::iterator vit;
vector<pair<long, long> > g;
vector<long> pows;
vector<long> out;
set<pair<long, pair<long, long> > > res;
long M, Mtank, Mtap;
;
void dfs(long i, long par) {
  if (g[i].first == -1) {
    Mtap = i;
    return;
  }
  if (par == -1) Mtank = i;
  M = min(g[i].second, M);
  dfs(g[i].first, i);
}
int main() {
  long n, m;
  cin >> n >> m;
  pows.assign(n + 1, 0);
  out.assign(n + 1, 0);
  g.assign(n + 1, make_pair(-1, 0));
  long tank, tap, d;
  for (int i = 0; i < m; ++i) {
    cin >> tank >> tap >> d;
    g[tank] = make_pair(tap, d);
    pows[tap]++;
    out[tank]++;
  }
  for (int i = 1; i < g.size(); ++i) {
    if (pows[i] == 0 && out[i]) {
      M = 2147483643;
      dfs(i, -1);
      res.insert(make_pair(Mtank, make_pair(Mtap, M)));
    }
  }
  cout << res.size() << endl;
  for (set<pair<long, pair<long, long> > >::iterator it = res.begin();
       it != res.end(); ++it) {
    cout << it->first << ' ' << it->second.first << ' ' << it->second.second
         << endl;
  }
  return 0;
}
