#include <bits/stdc++.h>
using namespace std;
struct path {
  int prev;
  int next;
} v[1010];
struct ans {
  int x;
  int y;
  int z;
} temp;
vector<ans> g;
int mincost[1010];
int mint = 100000000;
bool visit[1010];
int flow(int i) {
  visit[i] = true;
  if (mint > mincost[i]) mint = mincost[i];
  if (v[i].next == 0)
    return i;
  else
    return flow(v[i].next);
}
int main() {
  int n, p, a, b, d, i;
  cin >> n >> p;
  for (i = 0; i <= n; i++) {
    v[i].next = 0;
    v[i].prev = 0;
    mincost[i] = 100000000;
  }
  for (i = 0; i < p; i++) {
    cin >> a >> b >> d;
    v[a].next = b;
    v[b].prev = a;
    mincost[b] = d;
  }
  for (i = 1; i <= n; i++) {
    mint = 10000000;
    if (v[i].prev == 0 && v[i].next != 0 && visit[i] == false) {
      temp.x = i;
      temp.y = flow(i);
      temp.z = mint;
      g.push_back(temp);
    }
  }
  cout << g.size() << endl;
  for (i = 0; i < g.size(); i++) {
    cout << g[i].x << ' ' << g[i].y << ' ' << g[i].z << endl;
  }
  return 0;
}
