#include <bits/stdc++.h>
using namespace std;
struct res {
  int a;
  int b;
  int d;
};
int main() {
  int n, p;
  int min;
  int a, b;
  int j;
  cin >> n >> p;
  int d[n + 1];
  int x[n + 1];
  int y[n + 1];
  map<int, int> m;
  memset(x, 0, sizeof(x));
  memset(y, 0, sizeof(y));
  for (int i = 0; i < p; i++) {
    cin >> a >> b;
    cin >> d[a];
    m[a] = b;
    x[a] = 1;
    y[b] = 1;
  }
  int t = 0;
  struct res ob;
  vector<struct res> v;
  for (int i = 1; i <= n; i++) {
    if (x[i] == 1 && y[i] == 0) {
      t++;
      j = i;
      min = d[i];
      while (m[j]) {
        j = m[j];
        if (min > d[j] && m[j] != 0) min = d[j];
      }
      ob.a = i;
      ob.b = j;
      ob.d = min;
      v.push_back(ob);
    }
  }
  cout << t << endl;
  for (int i = 0; i < t; i++)
    cout << v[i].a << " " << v[i].b << " " << v[i].d << endl;
  return 0;
}
