#include <bits/stdc++.h>
using namespace std;
vector<long long> adj[1002];
map<long long, long long> vis;
map<pair<long long, long long>, long long> dia;
long long st[1002], en[1002];
void dfs(long long tar, long long cur, bool &found, long long mini,
         long long &mini2) {
  vis[cur] = 1;
  if (tar == cur) {
    found = true;
    mini2 = min(mini, mini2);
    return;
  }
  for (long long i = 0; i < adj[cur].size(); i++) {
    if (vis[adj[cur][i]] == 0) {
      dfs(tar, adj[cur][i], found, min(mini, dia[{cur, adj[cur][i]}]), mini2);
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long t, n, num, m, k;
  cin >> n >> k;
  for (long long i = 0; i < k; i++) {
    long long a, b, d;
    cin >> a >> b >> d;
    adj[a].push_back(b);
    adj[b].push_back(a);
    st[a]++;
    en[b]++;
    dia[{a, b}] = d;
    dia[{b, a}] = d;
  }
  vector<long long> v1, v2;
  for (long long i = 1; i <= n; i++) {
    if (en[i] == 0 && st[i] == 1) {
      v1.push_back(i);
    }
    if (st[i] == 0 && en[i] == 1) {
      v2.push_back(i);
    }
  }
  cout << v1.size() << '\n';
  for (long long i = 0; i < v1.size(); i++) {
    for (long long j = 0; j < v2.size(); j++) {
      bool found = false;
      long long mini2 = LLONG_MAX;
      dfs(v2[j], v1[i], found, LLONG_MAX, mini2);
      vis.clear();
      if (found) {
        cout << v1[i] << " " << v2[j] << " " << mini2 << '\n';
      }
    }
  }
  return 0;
}
