#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3F3F3F3F;
const long long LINF = 0x3F3F3F3F3F3F3F3FLL;
const double EPS = 1E-10;
inline int cmp(double x, double y = 0, double tol = EPS) {
  return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1;
}
int N, P;
int adj[1010], cost[1010];
int in[1010];
int mini, out;
int RET[1010][3], K;
void dfs(int u, int p) {
  out = u;
  if (adj[u] == p) {
    out = -1;
    return;
  }
  if (adj[u]) {
    mini = min(mini, cost[u]);
    dfs(adj[u], p);
  }
}
int main() {
  scanf("%d %d", &N, &P);
  for (int(i) = (0); (i) < (P); (i)++) {
    int u, v, d;
    scanf("%d %d %d", &u, &v, &d);
    adj[u] = v;
    cost[u] = d;
    in[v]++;
  }
  K = 0;
  for (int(i) = (1); (i) < (N + 1); (i)++)
    if (!in[i] && adj[i]) {
      mini = INF;
      dfs(i, i);
      if (out != -1) RET[K][0] = i, RET[K][1] = out, RET[K][2] = mini, K++;
    }
  printf("%d\n", K);
  for (int(i) = (0); (i) < (K); (i)++)
    printf("%d %d %d\n", RET[i][0], RET[i][1], RET[i][2]);
  return 0;
}
