#include <bits/stdc++.h>
using namespace std;
void read(long long a = 0) {
  freopen("in", "r", stdin);
  if (a) freopen("out", "w", stdout);
}
vector<vector<pair<long long, long long> > > ad;
long long over;
long long dfs(long long a) {
  over = a;
  if (ad[a].size() == 0) return 1000000007;
  return min(ad[a][0].second, dfs(ad[a][0].first));
}
int main() {
  long long n;
  cin >> n;
  long long m;
  ad = vector<vector<pair<long long, long long> > >(n + 1);
  cin >> m;
  bool vis[10000] = {}, good[10000] = {};
  while (m--) {
    long long x, y, d;
    cin >> x >> y >> d;
    x--, y--;
    vis[y] = 1;
    good[x] = 1;
    ad[x].push_back(make_pair(y, d));
  }
  vector<pair<pair<long long, long long>, long long> > ans;
  for (int i = 0; i < n; i++) {
    if (!vis[i] && good[i]) {
      pair<pair<long long, long long>, long long> tmp;
      tmp.first.first = i;
      tmp.second = dfs(i);
      tmp.first.second = over;
      ans.push_back(tmp);
    }
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << "\n";
  for (int i = 0; i < ans.size(); i++)
    cout << ans[i].first.first + 1 << " " << ans[i].first.second + 1 << " "
         << ans[i].second << "\n";
}
