#include <bits/stdc++.h>
int IntMaxVal = (int)1e20;
long long LongMaxVal = (long long)1e20;
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  ;
  int m;
  cin >> m;
  ;
  vector<int> goesTo(n + 1, -1);
  vector<int> diamTo(n + 1);
  vector<bool> hasIn(n + 1);
  for (int i = 1; i < m + 1; ++i) {
    int from;
    cin >> from;
    ;
    int to;
    cin >> to;
    ;
    int d;
    cin >> d;
    ;
    hasIn[to] = true;
    goesTo[from] = to;
    diamTo[from] = d;
  }
  vector<int> tank;
  vector<int> tap;
  vector<int> diam;
  for (int i = 1; i < n + 1; ++i)
    if (!hasIn[i] && goesTo[i] != -1) {
      int d = diamTo[i];
      int tmp = goesTo[i];
      while (goesTo[tmp] != -1) {
        { d = min(d, diamTo[tmp]); };
        tmp = goesTo[tmp];
      }
      tank.push_back(i);
      tap.push_back(tmp);
      diam.push_back(d);
    }
  cout << tank.size() << endl;
  for (int i = 0; i < tank.size() - 1 + 1; ++i) {
    cout << tank[i] << ' ' << tap[i] << ' ' << diam[i] << endl;
  }
}
