#include <bits/stdc++.h>
using namespace std;
struct Result {
  int tank, tap, diameter;
  Result() : tank(0), tap(0), diameter(0) {}
  Result(int a, int b, int c) : tank(a), tap(b), diameter(c) {}
  bool operator<(const Result& a) const { return tank < a.tank; }
};
int n, p, es[1002][1002], a, b, res_size;
bool used[1002];
Result result[1002];
void dfs(int from, int cur, int meter) {
  if (used[cur]) return;
  used[cur] = true;
  for (int i = 0; i < (int)n; i++)
    if (es[cur][i] > 0) {
      dfs(from, i, min(meter, es[cur][i]));
      return;
    }
  if (from != cur) {
    result[res_size] = Result(from + 1, cur + 1, meter);
    res_size++;
  }
}
int main(int argc, char* argv[]) {
  memset(es, -1, sizeof es);
  set<int> taps;
  cin >> n >> p;
  for (int i = 0; i < (int)p; i++) {
    cin >> a >> b;
    a--;
    b--;
    taps.insert(b);
    cin >> es[a][b];
  }
  fill(used, used + n, false);
  for (int i = 0; i < (int)n; i++) {
    if (!used[i] && !taps.count(i)) dfs(i, i, 1 << 28);
  }
  if (res_size) {
    sort(result, result + res_size);
    printf("%d\n", res_size);
    for (int i = 0; i < (int)res_size; i++)
      printf("%d %d %d\n", result[i].tank, result[i].tap, result[i].diameter);
  } else {
    puts("0");
  }
  return 0;
}
