#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > adj(500005);
int visited[500005];
int counter;
void dfs(int node, int color) {
  counter++;
  visited[node] = color;
  for (int i = 0; i < adj[node].size(); ++i) {
    if (visited[adj[node][i]] == 0) dfs(adj[node][i], color);
  }
  return;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int test = 1;
  while (test--) {
    int n, p, x, y;
    long long int d;
    cin >> n >> p;
    vector<vector<pair<int, long long int> > > orig(n);
    vector<vector<pair<int, long long int> > > term(n);
    for (int i = 0; i < p; ++i) {
      cin >> x >> y >> d;
      orig[x - 1].push_back({y - 1, d});
      term[y - 1].push_back({x - 1, d});
    }
    vector<pair<pair<int, int>, long long int> > v;
    for (int i = 0; i < n; ++i) {
      if (term[i].empty() && (!orig[i].empty())) {
        int start = i, ender;
        int j = i;
        long long int mini = orig[i][0].second;
        while (!orig[j].empty()) {
          mini = min(mini, orig[j][0].second);
          j = orig[j][0].first;
        }
        ender = j;
        v.push_back({{start, ender}, mini});
      }
    }
    cout << v.size() << endl;
    for (int i = 0; i < v.size(); ++i) {
      cout << v[i].first.first + 1 << " " << v[i].first.second + 1 << " "
           << v[i].second << endl;
    }
  }
  return 0;
}
