#include <bits/stdc++.h>
const int MAX_FLOW = 1000001;
int main() {
  int n, p;
  std::cin >> n >> p;
  std::vector<bool> src(n + 1, false);
  std::vector<std::pair<int, int> > sink(n + 1, std::make_pair(0, 0));
  for (int i = 0; i < p; i++) {
    int a, b, d;
    std::cin >> a >> b >> d;
    src[b] = true;
    sink[a] = std::make_pair(b, d);
  }
  std::vector<std::pair<std::pair<int, int>, int> > res;
  for (int i = 1; i <= n; i++) {
    if (src[i]) {
      continue;
    }
    int cur = i;
    int max_flow = MAX_FLOW;
    while (sink[cur].first) {
      max_flow = std::min(max_flow, sink[cur].second);
      cur = sink[cur].first;
    }
    if (cur != i) {
      std::pair<std::pair<int, int>, int> l =
          std::make_pair(std::make_pair(i, cur), max_flow);
      res.push_back(l);
    }
  }
  std::cout << res.size() << std::endl;
  for (int i = 0; i < (int)res.size(); i++) {
    std::cout << res[i].first.first << " " << res[i].first.second << " "
              << res[i].second << std::endl;
  }
}
