#include <bits/stdc++.h>
using namespace std;
int diam[1005][1005];
int t[1005][3];
int it = 0;
int In[1005], Out[1005];
int main() {
  int n, p;
  cin >> n >> p;
  for (int i = 0; i < n; i++) In[i] = Out[i] = -1;
  for (int i = 0; i < p; i++) {
    int a, b, d;
    cin >> a >> b >> d;
    a--;
    b--;
    In[b] = a;
    Out[a] = b;
    diam[a][b] = d;
  }
  for (int i = 0; i < n; i++) {
    if (In[i] == -1 && Out[i] != -1) {
      int now = i;
      int tank = i;
      int tap = -1;
      int d = -1;
      while (Out[now] != -1) {
        if (d == -1 || diam[now][Out[now]] < d) d = diam[now][Out[now]];
        now = Out[now];
        tap = now;
      }
      t[it][0] = tank;
      t[it][1] = tap;
      t[it][2] = d;
      it++;
    }
  }
  cout << it << endl;
  for (int i = 0; i < it; i++)
    cout << t[i][0] + 1 << ' ' << t[i][1] + 1 << ' ' << t[i][2] << endl;
  return 0;
}
