#include <bits/stdc++.h>
using namespace std;
const long long mx = 105;
const long long mod = 1e9 + 7;
const long long maxn = 1e7;
vector<vector<pair<long long, long long>>> adj;
bool vis[maxn];
long long cr, en;
void dfs(long long v, long long p) {
  en = v;
  for (auto it : adj[v]) {
    if (it.first != p) {
      cr = min(cr, it.second);
      dfs(it.first, v);
    }
  }
}
void solve() {
  long long n, i, j, k, p;
  cin >> n >> p;
  adj.clear();
  adj.resize(n + 1);
  bool out[n + 1], inc[n + 1];
  memset(out, 0, sizeof(out));
  memset(inc, 0, sizeof(inc));
  for (i = 0; i < p; i++) {
    long long a, b, c;
    cin >> a >> b >> c;
    adj[a].push_back({b, c});
    out[a] = true;
    inc[b] = true;
  }
  memset(vis, 0, sizeof(vis));
  long long no = 0;
  for (i = 1; i <= n; i++) {
    if (out[i] && !inc[i]) {
      no++;
    }
  }
  cout << no << "\n";
  for (i = 1; i <= n; i++) {
    if (out[i] && !inc[i]) {
      cr = 1e18;
      dfs(i, -1);
      cout << i << " " << en << " " << cr << "\n";
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long t = 1, i, j, k;
  while (t--) {
    solve();
  }
}
