#include <bits/stdc++.h>
using namespace std;
const int mxn = 1024;
int n, p;
int in[mxn], out[mxn];
vector<int> adj[mxn];
int vis[mxn];
int main(int argc, char** argv) {
  scanf("%d", &n);
  scanf("%d", &p);
  for (int i = 0; i < p; i++) {
    int f, t, d;
    scanf("%d", &f);
    scanf("%d", &t);
    scanf("%d", &d);
    in[t]++;
    out[f]++;
    adj[f].push_back(t);
    adj[f].push_back(d);
  }
  memset(vis, 0, sizeof vis);
  vector<pair<pair<int, int>, int> > sol;
  for (int i = 1; i <= n; i++) {
    if (out[i] == 1 && in[i] == 0) {
      int v = i;
      int minD = (int)2e9;
      while (adj[v].size() > 0) {
        minD = min(minD, adj[v][1]);
        v = adj[v][0];
      }
      sol.push_back(make_pair(make_pair(i, v), minD));
    }
  }
  sort(sol.begin(), sol.end());
  printf("%d\n", sol.size());
  for (int i = 0; i < sol.size(); i++) {
    printf("%d %d %d\n", sol[i].first.first, sol[i].first.second,
           sol[i].second);
  }
  return 0;
}
