#include <bits/stdc++.h>
using namespace std;
signed main() {
  long long int n, m;
  cin >> n >> m;
  if (m == 0) {
    cout << 0;
    return 0;
  }
  vector<vector<long long int>> v[n + 1];
  long long int in[n + 1];
  memset(in, 0, sizeof(in));
  for (long long int i = 0; i < m; i++) {
    long long int x, y, z;
    cin >> x >> y >> z;
    v[x].push_back({y, z});
    in[y] += 1;
  }
  queue<vector<long long int>> q;
  for (long long int i = 1; i <= n; i++) {
    if (in[i] == 0 && v[i].size()) {
      q.push({i, INT_MAX, i});
    }
  }
  vector<vector<long long int>> ans;
  while (q.size()) {
    vector<long long int> p = q.front();
    q.pop();
    if (p.size() && v[p[0]].size() == 0) {
      ans.push_back({p[2], p[0], p[1]});
    }
    for (auto x : v[p[0]]) {
      in[x[0]] -= 1;
      if (in[x[0]] == 0) {
        q.push({x[0], min(p[1], x[1]), p[2]});
      }
    }
  }
  cout << ans.size() << "\n";
  sort(ans.begin(), ans.end());
  for (auto x : ans) {
    for (auto y : x) cout << y << " ";
    cout << "\n";
  }
}
