#include <bits/stdc++.h>
using namespace std;
int n, p;
int indegre[1010];
pair<int, int> outdegre[1010];
int visited[1010];
pair<int, int> dfs(int node) {
  pair<int, int> r;
  if (outdegre[node].first != -1) {
    r = dfs(outdegre[node].first);
    r.second = min(r.second, outdegre[node].second);
  } else {
    r.first = node;
    r.second = 10000000;
  }
  return r;
}
int main() {
  cin >> n >> p;
  memset(indegre, -1, sizeof(indegre));
  memset(outdegre, -1, sizeof(outdegre));
  int x, y, cost;
  for (int i = 0; i < p; i++) {
    cin >> x >> y >> cost;
    x--;
    y--;
    indegre[y] = x;
    outdegre[x] = pair<int, int>(y, cost);
  }
  vector<pair<pair<int, int>, int> > ret;
  for (int i = 0; i < n; i++)
    if (indegre[i] == -1 && outdegre[i].first != -1) {
      pair<pair<int, int>, int> r;
      pair<int, int> d = dfs(i);
      r.first.first = i;
      r.first.second = d.first;
      r.second = d.second;
      ret.push_back(r);
    }
  sort(ret.begin(), ret.end());
  cout << ((int)(ret).size()) << endl;
  for (int i = 0; i < ((int)(ret).size()); i++)
    cout << ret[i].first.first + 1 << " " << ret[i].first.second + 1 << " "
         << ret[i].second << endl;
  return 0;
}
