#include <bits/stdc++.h>
using namespace std;
const int MAX = 1009;
int n, p, diam[MAX], adjmat[MAX];
bool vis[MAX];
int from[MAX], to[MAX], mxxdi[MAX];
int main() {
  int ret = 0;
  cin >> n >> p;
  while (p--) {
    int foo, bar, dim;
    cin >> foo >> bar >> dim;
    adjmat[foo] = bar, diam[foo] = dim, vis[bar] = 1;
  }
  for (int i = 1; i <= n; i++) {
    if (vis[i]) continue;
    int foo = i, bar = 1e7;
    while (adjmat[foo]) bar = min(bar, diam[foo]), foo = adjmat[foo];
    if (i == foo) continue;
    from[ret] = i, to[ret] = foo, mxxdi[ret] = bar, ret++;
  }
  cout << ret << endl;
  for (int i = 0; i < ret; i++)
    cout << from[i] << " " << to[i] << " " << mxxdi[i] << endl;
}
