#include <bits/stdc++.h>
using namespace std;
const int oo = (1 << 29);
const int N = 1024;
int indeg[N], outdeg[N];
int dis[N][N];
int net[N][N];
bool vis[N];
int n, m;
int tmp;
void dfs(int sta, int u) {
  vis[u] = true;
  for (int i = 1; i <= n; i++) {
    if (!vis[i] && net[u][i]) {
      tmp = min(tmp, net[u][i]);
      dfs(sta, i);
    }
  }
  dis[sta][u] = tmp;
}
int main() {
  while (scanf("%d %d", &n, &m) == 2) {
    if (n == 1) {
      printf("0\n");
      continue;
    }
    memset(indeg, 0, sizeof(indeg));
    memset(outdeg, 0, sizeof(outdeg));
    memset(vis, false, sizeof(vis));
    memset(net, 0, sizeof(net));
    fill(dis[0], dis[0] + N * N, oo);
    for (int i = 1; i <= m; i++) {
      int u, v, w;
      scanf("%d %d %d", &u, &v, &w);
      net[u][v] = w;
      outdeg[u]++;
      indeg[v]++;
    }
    for (int i = 1; i <= n; i++) {
      if (!vis[i] && !indeg[i]) {
        tmp = oo;
        dfs(i, i);
      }
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= n; j++) {
        if (indeg[i] == 0 && outdeg[j] == 0) {
          if (dis[i][j] != oo) {
            ans++;
          }
        }
      }
    }
    printf("%d\n", ans);
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= n; j++) {
        if (indeg[i] == 0 && outdeg[j] == 0) {
          if (dis[i][j] != oo) {
            printf("%d %d %d\n", i, j, dis[i][j]);
          }
        }
      }
    }
  }
  return 0;
}
