#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > g[2000];
int N, M;
int degree[2000];
int main() {
  cin >> N >> M;
  for (int i = 0; i < M; i++) {
    int u, v, w;
    cin >> u >> v >> w;
    g[u].push_back({w, v});
    degree[v]++;
  }
  vector<pair<int, pair<int, int> > > A;
  for (int i = 1; i <= N; i++) {
    if (degree[i] == 0) {
      int ans = INT_MAX, j = i;
      while (g[j].size() != 0) {
        ans = min(ans, g[j][0].first);
        j = g[j][0].second;
      }
      if (ans != INT_MAX) {
        A.push_back({i, {j, ans}});
      }
    }
  }
  cout << A.size() << endl;
  for (auto node : A) {
    cout << node.first << " " << node.second.first << " " << node.second.second
         << endl;
  }
  return 0;
}
