#include <bits/stdc++.h>
using namespace std;
map<int, pair<int, int> > m;
void solve() {
  int n, p;
  cin >> n >> p;
  vector<int> from(n);
  vector<int> to(n);
  for (__typeof((p)) i = (0); i < (p); i += 1) {
    int a, b, c;
    cin >> a >> b >> c;
    a--;
    b--;
    from[a] = 1;
    to[b] = 1;
    m[a] = make_pair(b, c);
  }
  vector<vector<int> > ans;
  for (__typeof((n)) i = (0); i < (n); i += 1) {
    if (!to[i]) {
      int cur = INT_MAX;
      int j = i;
      while (from[j]) {
        cur = min(cur, m[j].second);
        j = m[j].first;
      }
      if (cur != INT_MAX) {
        vector<int> curans = {i + 1, j + 1, cur};
        ans.emplace_back(curans);
      }
    }
  }
  cout << (int)ans.size() << '\n';
  for (auto i : ans) {
    for (auto j : i) {
      cout << j << " ";
    }
    cout << '\n';
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
