#include <bits/stdc++.h>
using namespace std;
const int MAX_SZ = 1e6 + 2;
const int MOD = 1e9 + 7;
int t = 1, n, m, q, ql, qr;
char ch;
vector<vector<pair<int, int>>> adj;
vector<int> in_d, src;
vector<vector<int>> res;
int solve() {
  in_d.clear();
  in_d.resize(n);
  for (int i = 0; i < n; ++i) {
    for (auto p : adj[i]) {
      in_d[p.first]++;
    }
  }
  for (int i = 0; i < n; ++i) {
    if (in_d[i] == 0) {
      src.push_back(i);
    }
  }
  int btl, curr;
  for (auto s : src) {
    btl = INT_MAX;
    curr = s;
    while (adj[curr].size()) {
      btl = min(btl, adj[curr][0].second);
      curr = adj[curr][0].first;
    }
    if (s != curr) res.push_back({s + 1, curr + 1, btl});
  }
  sort(res.begin(), res.end());
  printf("%d\n", res.size());
  for (auto v : res) {
    printf("%d %d %d\n", v[0], v[1], v[2]);
  }
  return 0;
}
int main() {
  while (t--) {
    scanf("%d%d", &n, &m);
    adj.clear();
    adj.resize(n);
    for (int i = 0; i < m; ++i) {
      scanf("%d%d%d", &ql, &qr, &q);
      adj[ql - 1].push_back({qr - 1, q});
    }
    solve();
  }
}
