#include <bits/stdc++.h>
using namespace std;
pair<int, int> a[10001];
int drom(int r) {
  if (a[r].first != 0) {
    int u = r;
    r = a[r].first;
    if (a[r].second != 0)
      a[r].second = min(a[r].second, a[u].second);
    else
      a[r].second = a[u].second;
    a[u].first = 0;
  } else
    return r;
  r = drom(r);
  return r;
}
int n, t, l;
int main() {
  cin >> n >> t;
  while (t != 0) {
    int x, y, z;
    cin >> x >> y >> z;
    a[x].first = y;
    a[x].second = z;
    t--;
  }
  for (int i = 1; i <= n; ++i) {
    int m = drom(i);
    if (m != i) {
      a[i].first = m;
      a[i].second = a[m].second;
    } else {
      a[i].first = 0;
    }
  }
  for (int i = 1; i <= n; ++i)
    if (a[i].first != 0) l++;
  cout << l << endl;
  for (int i = 1; i <= n; ++i)
    if (a[i].first != 0)
      cout << i << " " << a[i].first << " " << a[i].second << endl;
}
