#include <bits/stdc++.h>
using namespace std;
const int N = 1234;
int tap, diameter, cnt;
vector<pair<int, int>> G[N];
bool used[N], in[N], out[N];
void dfs(int i) {
  used[i] = 1;
  tap = i;
  cnt++;
  for (auto [v, cost] : G[i]) {
    if (used[v]) {
      cnt = -1e9;
      return;
    }
    diameter = min(diameter, cost);
    dfs(v);
  }
}
int main() {
  int n, p;
  cin >> n >> p;
  vector<pair<int, pair<int, int>>> ans;
  for (int i = 0; i < p; i++) {
    int u, v, cost;
    cin >> u >> v >> cost;
    in[v] = 1;
    out[u] = 1;
    G[u].push_back({v, cost});
  }
  for (int i = 1; i <= n; i++) {
    if (out[i] && !in[i]) {
      cnt = 0;
      diameter = 1e9;
      dfs(i);
      if (cnt > 1) ans.push_back({i, {tap, diameter}});
    }
  }
  cout << ans.size() << endl;
  for (auto [u, p] : ans) {
    auto [v, cost] = p;
    cout << u << " " << v << " " << cost << endl;
  }
}
