#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, p, u, v, w;
  cin >> n >> p;
  int in[n + 1], out[n + 1], d[n + 1];
  memset(in, -1, sizeof(in)), memset(out, -1, sizeof(out));
  for (int i = 0; i < p; i++) {
    cin >> u >> v >> w;
    in[v] = u, d[v] = w, out[u] = v;
  }
  int cnt = 0;
  for (int i = 1; i < n + 1; i++)
    if (in[i] == -1 && out[i] != -1) cnt++;
  cout << cnt << endl;
  for (int i = 1; i < n + 1; i++) {
    v = i;
    if (in[v] == -1 && out[v] != -1) {
      cnt = INT_MAX;
      while (out[v] != -1) {
        cnt = min(cnt, d[out[v]]);
        v = out[v];
      }
      cout << i << " " << v << " " << cnt << endl;
    }
  }
  return 0;
}
long long choose(long long n, long long k) {
  if (k == 0) return 1;
  return (n * choose(n - 1, k - 1)) / k;
}
bool isprime(long long n) {
  for (long long i = 2; i * i <= n; i++) {
    if (n % i == 0) return false;
  }
  return true;
}
int gcd(int a, int b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
int power(int x, int y, int p) {
  int res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
