#include <bits/stdc++.h>
using namespace std;
long long pow(long long a, long long b) {
  if (b == 1) {
    return a;
  }
  if (b % 2 == 1) {
    return pow(a, b - 1) * a;
  } else {
    long long x = pow(a, b / 2);
    return x * x;
  }
}
long long powm(long long a, long long b, long long m) {
  if (b == 0) {
    return 1;
  }
  if (b == 1) {
    return a % m;
  }
  if (b % 2 == 1) {
    return ((powm(a, b - 1, m) % m) * (a % m)) % m;
  } else {
    long long x = powm(a, b / 2, m);
    return ((x % m) * (x % m)) % m;
  }
}
long long gcd(long long a, long long b) {
  long long re = b % a;
  if (re == 0) {
    return a;
  }
  return gcd(re, a);
}
long long q[1005][1005], v[1005], vis[1005], vis1[1005], par[1005], mini, endi;
vector<long long> tank, tap, diameter;
long long dfs(long long k) {
  vis[k] = 1;
  if (v[k] == 0) {
    if (par[k] == 0) {
      return 0;
    } else {
      endi = k;
      return 1;
    }
  } else {
    if (vis[v[k]] == 1) {
      return 0;
    } else {
      mini = min(mini, q[k][v[k]]);
      dfs(v[k]);
    }
  }
}
int main() {
  long long h, p;
  cin >> h >> p;
  long long a, b, d;
  for (long long i = 0; i < p; i++) {
    cin >> a >> b >> d;
    par[b] = a;
    q[a][b] = d;
    v[a] = b;
  }
  long long ans = 0;
  for (long long i = 1; i <= h; i++) {
    if (par[i] == 0) {
      if (vis[i] == 0) {
        mini = 10000000;
        endi = 0;
        if (dfs(i)) {
          ans++;
          tank.push_back(i);
          tap.push_back(endi);
          diameter.push_back(mini);
        }
      }
    }
  }
  cout << ans << endl;
  for (long long j = 0; j < ans; j++) {
    cout << tank[j] << " " << tap[j] << " " << diameter[j] << endl;
  }
  return 0;
}
