#include <bits/stdc++.h>
using namespace std;
int vis[1005];
map<int, pair<int, int> > nex;
map<int, int> pre;
vector<pair<int, pair<int, int> > > li;
void func(int dx) {
  int mi = 999999;
  int x = dx;
  while (nex[x].first) {
    mi = min(mi, nex[x].second);
    x = nex[x].first;
  }
  if (dx != x) {
    li.push_back(make_pair(dx, make_pair(x, mi)));
  }
}
int main() {
  int n, p;
  int i, j, k, l;
  cin >> n >> p;
  for (i = 0; i < p; i++) {
    vis[i] = 0;
    cin >> j >> k >> l;
    nex[j] = make_pair(k, l);
    pre[k] = j;
  }
  for (i = 1; i <= n; i++) {
    if (!pre[i]) {
      func(i);
    }
  }
  sort(li.begin(), li.end());
  cout << li.size() << endl;
  for (i = 0; i < li.size(); i++) {
    cout << li[i].first << " " << li[i].second.first << " "
         << li[i].second.second << endl;
  }
  return 0;
}
