#include <bits/stdc++.h>
using namespace std;
vector<pair<long long int, long long int> > g[300005];
bool u[300005];
long long int arr[300005], z;
long long int in[500005], out[500005];
long long int dfs(long long int v) {
  u[v] = true;
  if (out[v] == 0) return v;
  for (int i = 0; i < g[v].size(); i++) {
    if (u[g[v][i].first] == false) {
      z = min(z, g[v][i].second);
      return dfs(g[v][i].first);
    }
  }
}
int main() {
  long long int i, j, n, m, ans = 0, a, b, c, index = 1;
  cin >> n >> m;
  for (i = 1; i <= m; i++) {
    cin >> a >> b >> c;
    g[a].push_back(make_pair(b, c));
    in[b]++;
    out[a]++;
  }
  set<pair<pair<int, int>, int> > s;
  for (i = 1; i <= n; i++) {
    if (in[i] == 0 && out[i] != 0) {
      z = INT_MAX;
      int k = dfs(i);
      s.insert(make_pair(make_pair(i, k), z));
    }
  }
  cout << s.size() << endl;
  for (auto it = s.begin(); it != s.end(); it++) {
    cout << it->first.first << " " << it->first.second << " " << it->second
         << endl;
  }
  return 0;
}
