#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long>> ar[1005];
vector<long long> arr[1005];
bool vis[1005];
long long ln = 0;
long long dfs(long long s, long long m) {
  vis[s] = 1;
  if (ar[s].empty()) ln = s;
  for (auto it : ar[s]) {
    m = min(m, dfs(it.first, it.second));
  }
  return m;
}
signed main() {
  long long t;
  t = 1;
  while (t--) {
    long long n, p;
    cin >> n >> p;
    if (!p)
      cout << 0;
    else {
      long long k = p;
      long long a, b, c;
      while (k--) {
        cin >> a >> b >> c;
        ar[a].push_back({b, c});
        arr[b].push_back(a);
      }
      vector<long long> dfsw;
      for (long long i = 1; i <= n; i++) {
        if (arr[i].empty() && !ar[i].empty()) dfsw.push_back(i);
      }
      long long si = dfsw.size();
      vector<tuple<long long, long long, long long>> v;
      long long ct = 0;
      for (long long i = 0; i < si; i++) {
        ln = 0;
        long long k = dfs(dfsw[i], 1e9);
        v.push_back(make_tuple(dfsw[i], ln, k));
      }
      cout << v.size() << endl;
      for (auto it : v) {
        cout << get<0>(it) << " " << get<1>(it) << " " << get<2>(it) << endl;
      }
    }
  }
  return 0;
}
