#include <bits/stdc++.h>
using namespace std;
int out[1000];
int d[1000];
int hv[1000];
bool cmp(pair<int, pair<int, int> > a, pair<int, pair<int, int> > b) {
  return a.first < b.first;
}
pair<int, pair<int, int> > res[1000];
int main() {
  memset(out, -1, sizeof(out));
  memset(hv, 0, sizeof(hv));
  int n, p;
  int x, y, z;
  cin >> n >> p;
  for (int i = 0; i < p; ++i) {
    cin >> x >> y >> z;
    --x;
    --y;
    out[x] = y;
    d[x] = z;
    hv[y] = 1;
  }
  int rs = 0;
  for (int i = 0; i < n; ++i)
    if (out[i] != -1 && !hv[i]) {
      pair<int, pair<int, int> > t;
      int dd = d[i];
      t.first = i + 1;
      int j = out[i];
      while (out[j] != -1) {
        dd = min(d[j], dd);
        j = out[j];
      }
      t.second.first = j + 1;
      t.second.second = dd;
      res[rs++] = t;
    }
  sort(res, res + rs, cmp);
  cout << rs << endl;
  for (int i = 0; i < rs; ++i) {
    cout << res[i].first << ' ' << res[i].second.first << ' '
         << res[i].second.second << endl;
  }
  return 0;
}
