#include <bits/stdc++.h>
using namespace std;
int child[1005];
int dia[1005];
int tank[1005];
int ntank[1005];
set<pair<int, pair<int, int> > > ans;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, p, a, b, c;
  cin >> n >> p;
  for (int i = 1; i <= n; i++) {
    child[i] = -1;
    tank[i] = 1;
    ntank[i] = 0;
  }
  for (int i = 1; i <= p; i++) {
    cin >> a >> b >> c;
    tank[b] = 0;
    ntank[a] = 1;
    dia[b] = c;
    child[a] = b;
  }
  for (int i = 1; i <= n; i++)
    if (tank[i] == 1 && ntank[i] == 1) {
      a = i;
      c = 100000000;
      while (child[a] > 0) {
        a = child[a];
        c = min(c, dia[a]);
      }
      ans.insert({i, {a, c}});
    }
  cout << ans.size() << ("\n");
  for (auto u : ans) {
    cout << u.first << " " << u.second.first << " " << u.second.second
         << ("\n");
  }
  return 0;
}
