#include <bits/stdc++.h>
using namespace std;
bool isprime[2000005];
void setprime() {
  for (long long i = 0; i < 2000005; i++) isprime[i] = true;
  isprime[0] = false;
  isprime[1] = false;
  for (long long i = 2; i < 2000005; i++) {
    for (long long j = 2; i * j < 2000005; j++) isprime[i * j] = false;
  }
}
long long choose(long long n, long long k) {
  if (k == 0) return 1;
  return (n * choose(n - 1, k - 1)) / k;
}
long long gcd(long long a, long long b) {
  if (!a) return b;
  return gcd(b % a, a);
}
long long n, m, temp;
pair<long long, long long> p[100005];
bool start[100005];
vector<pair<pair<long long, long long>, long long> > ans;
long long min1 = LONG_LONG_MAX;
long long end1;
void dfs(long long x) {
  if (p[x].first != 0) {
    min1 = min(min1, p[x].second);
    dfs(p[x].first);
  } else {
    end1 = x;
    return;
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (long long i = 0; i < m; i++) {
    long long u, v, w;
    cin >> u >> v >> w;
    p[u] = make_pair(v, w);
    start[v] = 1;
  }
  for (long long i = 1; i < n + 1; i++) {
    if (!start[i]) {
      min1 = LONG_LONG_MAX;
      end1 = -1;
      dfs(i);
      if (min1 != LONG_LONG_MAX)
        ans.push_back(make_pair(make_pair(i, end1), min1));
    }
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << endl;
  for (long long i = 0; i < ans.size(); i++) {
    cout << ans[i].first.first << " " << ans[i].first.second << " "
         << ans[i].second << endl;
  }
}
