#include <bits/stdc++.h>
using namespace std;
struct node {
  int v, w, next;
} a[222222];
int start[1111], tot = 0;
int n, m;
int ans[1111][1111];
vector<pair<int, int> > t;
int in[1111], out[1111];
int v[1111];
int mn, p;
void dfs(int u) {
  v[u] = 1;
  if (out[u] == 0) p = u;
  for (int i = start[u]; ~i; i = a[i].next) {
    if (!v[a[i].v]) {
      mn = min(mn, a[i].w);
      dfs(a[i].v);
    }
  }
}
int main() {
  memset(start, -1, sizeof(start));
  tot = 0;
  int i, j, k;
  scanf("%d%d", &n, &m);
  for (i = 0; i < m; i++) {
    int q, w, e;
    scanf("%d%d%d", &q, &w, &e);
    a[tot].v = w;
    a[tot].w = e;
    a[tot].next = start[q];
    start[q] = tot++;
    ++in[w];
    ++out[q];
  }
  for (i = 1; i <= n; i++) {
    if (!in[i]) {
      if (!out[i]) continue;
      memset(v, 0, sizeof(v));
      mn = 11111111;
      dfs(i);
      ans[i][p] = mn;
      t.push_back(make_pair(i, p));
    }
  }
  sort(t.begin(), t.end());
  printf("%d\n", (int)((t).size()));
  for (int i = 0; i < (int)((t).size()); i++) {
    printf("%d %d %d\n", t[i].first, t[i].second, ans[t[i].first][t[i].second]);
  }
  return 0;
}
