#include <bits/stdc++.h>
using namespace std;
long long n, i, j, k, m;
long long c;
void solve() {
  cin >> n >> m;
  vector<pair<long long int, long long int>> v[n + 1];
  long long int in[n + 1];
  for (long long int i = 0; i < n + 1; i++) in[i] = 0;
  for (i = 0; i < m; i++) {
    cin >> j >> k >> c;
    v[j].push_back({k, c});
    in[k]++;
  }
  long long int vis[n + 1];
  for (long long int i = 0; i < n + 1; i++) vis[i] = 0;
  vector<pair<pair<long long int, long long int>, long long int>> ans;
  for (i = 1; i <= n; i++) {
    if (vis[i] == 0 && v[i].size() > 0 && in[i] == 0) {
      stack<pair<long long int, long long int>> s;
      s.push(v[i][0]);
      vis[i] = 1;
      long long int min1 = INT_MAX;
      while (!s.empty()) {
        pair<long long int, long long int> p = s.top();
        s.pop();
        min1 = min(min1, p.second);
        vis[p.first] = 1;
        if (v[p.first].size() == 0) {
          ans.push_back({{i, p.first}, min1});
          break;
        } else if (vis[p.first] == 1)
          if (vis[v[p.first][0].first] == 0) s.push(v[p.first][0]);
      }
    }
  }
  cout << ans.size() << endl;
  for (auto g : ans) {
    cout << g.first.first << " " << g.first.second << " " << g.second << endl;
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  long long int T = 1;
  long long h = T;
  while (T--) {
    solve();
    cout << endl;
  }
  return 0;
}
