#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  vector<pair<int, int>> graf(n + 1);
  vector<int> in(n + 1, 0);
  for (int i = 0; i < m; i++) {
    int a, b, w;
    scanf("%d%d%d", &a, &b, &w);
    in[b] = 1;
    graf[a] = make_pair(b, w);
  }
  vector<pair<pair<int, int>, int>> ans;
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0) {
      int mn = (int)1e9;
      int fir = i;
      int last = i;
      while (graf[last].first != 0) {
        mn = min(mn, graf[last].second);
        last = graf[last].first;
      }
      if (last != fir) {
        ans.push_back(make_pair(make_pair(fir, last), mn));
      }
    }
  }
  printf("%d\n", (int)ans.size());
  sort(ans.begin(), ans.end());
  for (int i = 0; i < (int)ans.size(); i++) {
    printf("%d %d %d\n", ans[i].first.first, ans[i].first.second,
           ans[i].second);
  }
  return 0;
}
