#include <bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
using namespace std;
int dfs(int node, int &min_cap, vector<bool> &vis,
        vector<pair<int, int>> adj[]) {
  vis[node] = 1;
  if (adj[node].size() == 0) return node;
  for (auto it : adj[node]) {
    int child = it.first, cap = it.second;
    if (cap < min_cap) min_cap = cap;
    if (!vis[child]) return dfs(child, min_cap, vis, adj);
  }
  return node;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, p;
  cin >> n >> p;
  vector<pair<int, int>> adj[n + 1];
  vector<bool> vis(n + 1, 0);
  vector<int> indeg(n + 1, 0), outdeg(n + 1, 0);
  for (int i = 1; i <= p; i++) {
    int u, v, d;
    cin >> u >> v >> d;
    adj[u].push_back({v, d});
    indeg[v]++, outdeg[u]++;
  }
  vector<int> tank, tap, pipe;
  for (int i = 1; i <= n; i++) {
    if (!vis[i] && indeg[i] == 0 && adj[i].size() == 1) {
      int min_cap = INT_MAX - 1;
      int v = dfs(i, min_cap, vis, adj);
      tank.push_back(i), tap.push_back(v), pipe.push_back(min_cap);
    }
  }
  if (tank.size() == 0)
    cout << 0;
  else {
    cout << tank.size() << "\n";
    for (int i = 0; i < tank.size(); i++)
      cout << tank[i] << " " << tap[i] << " " << pipe[i] << "\n";
  }
  return 0;
}
