#include <bits/stdc++.h>
using namespace std;
int P, N;
vector<pair<int, int> > in;
vector<pair<int, int> > out;
int main() {
  cin >> N >> P;
  in = vector<pair<int, int> >(N, pair<int, int>(0, 0));
  out = vector<pair<int, int> >(N, pair<int, int>(0, 0));
  for (int p = 0; p < P; p++) {
    int A, B, C;
    cin >> A >> B >> C;
    A--;
    B--;
    out[A].first = B;
    out[A].second = C;
    in[B].first = A;
    in[B].second = C;
  }
  vector<vector<int> > ans;
  for (int i = 0; i < N; i++) {
    if (in[i].second == 0 && out[i].second != 0) {
      int j = i;
      int mx = 999999999;
      while (out[j].second != 0) {
        mx = min(mx, out[j].second);
        j = out[j].first;
      }
      vector<int> v(3);
      v[0] = i + 1;
      v[1] = j + 1;
      v[2] = mx;
      ans.push_back(v);
    }
  }
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++) {
    for (int j = 0; j < 3; j++) {
      if (j > 0) cout << " ";
      cout << ans[i][j];
    }
    cout << endl;
  }
}
