#include <bits/stdc++.h>
const double pi = acos(-1);
const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const int MAXN = 1e5 + 5;
const double eps = 1e-9;
using namespace std;
int n, p, in[MAXN], out[MAXN];
vector<pair<int, int> > adj[MAXN];
void read() {
  scanf("%d", &(n)), scanf("%d", &(p));
  for (int i = 0; i < p; i++) {
    int u, v, w;
    scanf("%d", &(u)), scanf("%d", &(v)), scanf("%d", &(w));
    u--, v--;
    adj[u].push_back({v, w});
    in[v]++, out[u]++;
  }
}
pair<int, int> dfs(int u, int p) {
  int ret = INF, ind = -1;
  for (pair<int, int> nx : adj[u]) {
    pair<int, int> tmp = dfs(nx.first, u);
    ret = min(ret, min(tmp.second, nx.second));
    ind = tmp.first;
  }
  if (ind == -1) return {u, INF};
  return {ind, ret};
}
void solve() {
  int cnt = 0;
  for (int i = 0; i < n; i++)
    if (out[i] == 1 && in[i] == 0) cnt++;
  printf("%d\n", (cnt));
  for (int i = 0; i < n; i++) {
    if (out[i] != 1 || in[i] != 0) continue;
    pair<int, int> val = dfs(i, -1);
    printf("%d %d %d\n", i + 1, val.first + 1, val.second);
  }
}
int main() {
  read();
  solve();
  return 0;
}
