#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > E[1010];
int deg[1010], vis[1010];
vector<pair<int, pair<int, int> > > ans;
int N, P;
int main() {
  int u, v, d;
  while (~scanf("%d%d", &N, &P)) {
    for (int i = 0; i < N; i++) deg[i] = 0, E[i].clear();
    for (int i = 0; i < P; i++)
      scanf("%d%d%d", &u, &v, &d), u--, v--, deg[v]++,
          E[u].push_back(make_pair(v, d));
    ans.clear();
    for (int i = 0; i < N; i++)
      if (deg[i] == 0) {
        int dd = 1 << 30, u = i;
        for (u = i; E[u].size() > 0; u = E[u][0].first)
          dd = min(dd, E[u][0].second);
        if (dd < (1 << 30)) ans.push_back(make_pair(i, make_pair(u, dd)));
      }
    sort(ans.begin(), ans.end());
    printf("%d\n", ans.size());
    for (int i = 0; i < ans.size(); i++)
      printf("%d %d %d\n", ans[i].first + 1, ans[i].second.first + 1,
             ans[i].second.second);
  }
  return 0;
}
