#include <bits/stdc++.h>
#pragma comment(linker, "/stack:64000000")
using namespace std;
const int mx = 1000 + 10;
bool in[mx];
int nxt[mx];
int can[mx];
int main() {
  memset(in, 0, sizeof(in));
  memset(can, 0, sizeof(can));
  for (int(i) = 0; (i) < (mx); (i)++) nxt[i] = -1;
  int n, m;
  scanf("%d %d", &n, &m);
  for (int(i) = 0; (i) < (m); (i)++) {
    int a, b, d;
    scanf("%d %d %d", &a, &b, &d);
    in[b] = 1;
    nxt[a] = b;
    can[a] = d;
  }
  vector<pair<int, pair<int, int> > > r;
  for (int(i) = (1); (i) < (n + 1); (i)++) {
    if (!in[i] && nxt[i] != -1) {
      int k = i, d = can[k];
      while (nxt[k] != -1) {
        d = min(d, can[k]);
        k = nxt[k];
      }
      r.push_back(make_pair(i, make_pair(k, d)));
    }
  }
  sort((r).begin(), (r).end());
  printf("%d\n", (int)(r).size());
  for (int(i) = 0; (i) < ((int)(r).size()); (i)++) {
    printf("%d %d %d\n", r[i].first, r[i].second.first, r[i].second.second);
  }
  return 0;
}
