#include <bits/stdc++.h>
using namespace std;
struct Node {
  int in, out;
  int dout;
  Node() {
    in = -1;
    out = -1;
  }
};
Node v[1001];
int n, p;
int a, b, d;
vector<int> from, to, vol;
pair<int, int> pr;
pair<int, int> dfs(int i, int w) {
  if (v[i].out == -1) return make_pair(i, w);
  return dfs(v[i].out, min(w, v[i].dout));
}
int main() {
  scanf("%d %d", &n, &p);
  for (int i = 0; i < p; i++) {
    scanf("%d %d %d", &a, &b, &d);
    v[a].out = b;
    v[b].in = a;
    v[a].dout = d;
  }
  for (int i = 1; i <= n; i++)
    if (v[i].in == -1 && v[i].out != -1) {
      from.push_back(i);
      pr = dfs(i, v[i].dout);
      to.push_back(pr.first);
      vol.push_back(pr.second);
    }
  printf("%d\n", (int)vol.size());
  for (int i = 0; i < (int)vol.size(); i++)
    printf("%d %d %d\n", from[i], to[i], vol[i]);
  return 0;
}
