#include <bits/stdc++.h>
using namespace std;
long long a[100010], us[100010], user[100010];
vector<pair<long long, pair<long long, long long> > > ans;
vector<pair<long long, long long> > v[10000];
void dfs(long long x, long long p, long long mx) {
  us[x] = p;
  if (v[x].size() == 0 && x != p) ans.push_back({p, {x, mx}});
  for (int i = 0; i < v[x].size(); i++) {
    int to = v[x][i].first;
    if (us[to] != p) dfs(to, p, min(mx, v[x][i].second));
  }
}
int main() {
  long long n, i, x, y, z, m;
  cin >> n >> m;
  for (i = 1; i <= m; i++) {
    cin >> x >> y >> z;
    v[x].push_back({y, z});
    user[y] = 1;
  }
  for (i = 1; i <= n; i++)
    if (user[i] == 0) dfs(i, i, 10000000);
  cout << ans.size() << '\n';
  for (i = 0; i < ans.size(); i++)
    cout << ans[i].first << ' ' << ans[i].second.first << ' '
         << ans[i].second.second << '\n';
}
