#include <bits/stdc++.h>
using namespace std;
pair<long long int, long long int> dfs(long long int u, long long int dmin,
                                       pair<long long int, long long int> a[],
                                       pair<long long int, long long int> b[]) {
  long long int v = a[u].first;
  dmin = std::min(a[u].second, dmin);
  if (a[v].first == 0)
    return make_pair(v, dmin);
  else
    return dfs(v, dmin, a, b);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int m, t, n, i, f = 0, j, ans = 0, k, u, v, p;
  cin >> n >> p;
  pair<long long int, long long int> a[n + 1], b[n + 1];
  for (i = 0; i < n + 1; ++i) {
    a[i] = {0, 0};
    b[i] = {0, 0};
  }
  for (i = 0; i < p; ++i) {
    cin >> u >> v >> k;
    a[u] = make_pair(v, k);
    b[v] = make_pair(u, k);
  }
  vector<pair<long long int, long long int>> temp;
  vector<long long int> h;
  for (i = 1; i <= n; ++i) {
    if (b[i].first == 0) {
      if (a[i].first != 0) {
        temp.push_back(dfs(i, 1e8, a, b));
        h.push_back(i);
      }
    }
  }
  cout << temp.size() << endl;
  for (i = 0; i < temp.size(); ++i) {
    cout << h[i] << " " << temp[i].first << " " << temp[i].second << endl;
  }
  return 0;
}
