#include <bits/stdc++.h>
using namespace std;
struct ans {
  int f, t, v;
  ans() : f(0), t(0), v(0) {}
  ans(int f, int t, int v) : f(f), t(t), v(v) {}
};
vector<pair<int, int> > v;
vector<bool> w;
vector<ans> a;
int n;
pair<int, int> dfs(int f) {
  pair<int, int> res = make_pair(f, v[f].second);
  while (v[f].first != -1) {
    res.second = min(res.second, v[f].second);
    f = v[f].first;
  }
  res.first = f;
  return res;
}
int main() {
  cin >> n;
  int d, f, t, m;
  v.resize(n, make_pair(-1, -1));
  w.resize(n, false);
  cin >> m;
  for (int i = 0; i < m; i++) {
    cin >> f >> t >> d;
    --f;
    --t;
    v[f] = make_pair(t, d);
    w[t] = true;
  }
  pair<int, int> x;
  for (int i = 0; i < n; i++) {
    if (!w[i] && v[i].first != -1) {
      x = dfs(i);
      a.push_back(ans(i + 1, x.first + 1, x.second));
    }
  }
  cout << a.size() << endl;
  for (int i = 0; i < a.size(); i++)
    cout << a[i].f << " " << a[i].t << " " << a[i].v << endl;
}
