#include <bits/stdc++.h>
using namespace std;
struct triple {
  int a, b, c;
  triple(int x, int y, int z) : a(x), b(y), c(z){};
};
bool pred(const triple& a, const triple& b) {
  if (a.a < b.a)
    return 1;
  else
    return 0;
}
int main() {
  int n, p;
  scanf("%d%d", &n, &p);
  vector<pair<int, int> > v(n + 1), r(n + 1);
  vector<bool> u(n + 1);
  vector<triple> q;
  for (int i = 0; i < p; ++i) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    v[a] = make_pair(b, c);
    r[b] = make_pair(a, c);
  }
  for (int i = 1; i <= n; ++i) {
    if ((v[i].first != 0 || r[i].first != 0) && !u[i]) {
      int t = i;
      bool f = 0;
      while (r[t].first != 0) {
        if (u[t] == 1) {
          f = 1;
          break;
        }
        u[t] = 1;
        t = r[t].first;
      }
      u[t] = 1;
      if (f) continue;
      int a = t;
      int m = INT_MAX;
      while (v[t].first) {
        if (v[t].second < m) m = v[t].second;
        t = v[t].first;
        u[t] = 1;
      }
      q.push_back(triple(a, t, m));
    }
  }
  printf("%d\n", q.size());
  sort(q.begin(), q.end(), pred);
  for (int i = 0; i < q.size(); ++i)
    printf("%d %d %d\n", q[i].a, q[i].b, q[i].c);
}
