#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
bool prime(long long int n) {
  for (long long int i = 2; i * i <= n; i++) {
    if (n % i == 0) return false;
  }
  return true;
}
long long binexpm(long long a, long long b, long long m) {
  a %= m;
  long long res = 1;
  while (b > 0) {
    if (b & 1) res = res * a % m;
    a = a * a % m;
    b >>= 1;
  }
  return res;
}
long long binexp(long long a, long long b) {
  long long res = 1;
  while (b > 0) {
    if (b & 1) res = res * a;
    a = a * a;
    b >>= 1;
  }
  return res;
}
long long int n, p;
vector<long long int> adj[10001];
map<pair<long long int, long long int>, long long int> mp;
bool vis[10001] = {false};
map<pair<long long int, long long int>, long long int> res;
long long int x, y = -1;
long long int dm = INT_MAX;
bool xx = true;
long long int in[10001] = {0};
long long int out[10001] = {0};
bool dfs(long long int node) {
  if (vis[node]) xx = false;
  vis[node] = true;
  for (auto child : adj[node]) {
    dm = min(dm, mp[{node, child}]);
    if (adj[child].size() == 0) y = child;
    xx &= dfs(child);
  }
  return xx;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n >> p;
  for (long long int i = 0; i < p; i++) {
    long long int a, b, d;
    cin >> a >> b >> d;
    out[a]++;
    in[b]++;
    adj[a].push_back(b);
    mp[make_pair(a, b)] = d;
  }
  long long int ans = 0;
  for (long long int i = 1; i <= n; i++) {
    bool flag;
    dm = INT_MAX;
    if (out[i] == 1 && in[i] == 0) {
      x = i;
      flag = dfs(i);
      if (flag && y != -1) {
        ans++;
        res[make_pair(x, y)] = dm;
      }
    }
  }
  cout << ans << "\n";
  if (ans != 0) {
    for (auto it : res) {
      cout << it.first.first << " " << it.first.second << " " << it.second
           << "\n";
    }
  }
  return 0;
}
