#include <bits/stdc++.h>
using namespace std;
int n, m, a, b, c, in[1001];
struct SOL {
  int from, to, amount;
};
vector<SOL> res;
vector<vector<pair<int, int> > > v;
SOL bfs(int a) {
  queue<pair<int, int> > q;
  q.push(make_pair(a, 1 << 20));
  int mx = -1 << 20, l = -1;
  while (!q.empty()) {
    int f = q.front().first, am = q.front().second;
    q.pop();
    if (v[f].size() == 0) {
      mx = max(mx, am);
      l = f;
    }
    for (int i = 0; i < v[f].size(); i++)
      q.push(make_pair(v[f][i].first, min(v[f][i].second, am)));
  }
  SOL ret;
  if (a == l) {
    ret.amount = -1;
    return ret;
  }
  ret.from = a;
  ret.to = l;
  ret.amount = mx;
  return ret;
}
int main() {
  scanf("%d%d", &n, &m);
  v.resize(n + 1);
  for (int i = 0; i < m; i++) {
    scanf("%d%d%d", &a, &b, &c);
    v[a].push_back(make_pair(b, c));
    in[b]++;
  }
  SOL w;
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0) {
      SOL tmp;
      tmp = bfs(i);
      if (tmp.amount != -1) res.push_back(tmp);
    }
  }
  printf("%d\n", res.size());
  for (int i = 0; i < res.size(); i++)
    printf("%d %d %d\n", res[i].from, res[i].to, res[i].amount);
}
