#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline long long read() {
  long long x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
const int maxn = 1e5 + 10;
int n, m;
bool in[1005], out[1005];
int mp[1005], g[1005][1005];
struct node {
  int u, v, mx;
} ans[1005];
int main() {
  cin >> n >> m;
  memset(mp, -1, sizeof(mp));
  for (int i = 0; i < m; i++) {
    int u, v, w;
    cin >> u >> v >> w;
    in[v] = 1, out[u] = 1;
    g[u][v] = w;
    mp[u] = v;
  }
  int cnt = 0;
  for (int i = 1; i <= n; i++) {
    if (in[i] == 0 && out[i] != 0) {
      int u = i, v, t = INF;
      while (mp[u] != -1) {
        v = mp[u];
        t = min(t, g[u][v]);
        u = v;
      }
      ans[++cnt].u = i, ans[cnt].v = v, ans[cnt].mx = t;
    }
  }
  cout << cnt << endl;
  for (int i = 1; i <= cnt; i++)
    cout << ans[i].u << " " << ans[i].v << " " << ans[i].mx << endl;
  return 0;
}
