#include <bits/stdc++.h>
using namespace std;
int INF = 1000000000;
const long long MOD = 1e9 + 7;
vector<vector<pair<int, int> > > g;
bool hasIn[2000];
bool hasOut[2000];
int used[2000];
int curDfs = 1;
vector<int> first;
vector<int> second;
vector<int> cost;
void dfs(int v, int curMin = 1000000000) {
  if (g[v].size() == 0) {
    second.push_back(v);
    cost.push_back(curMin);
    return;
  }
  dfs(g[v][0].first, min(g[v][0].second, curMin));
}
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  int n;
  cin >> n;
  int p;
  cin >> p;
  g.resize(n + 1);
  for (int i = 0; i < p; ++i) {
    int x, y, d;
    cin >> x >> y >> d;
    g[x].push_back(make_pair(y, d));
    hasIn[y] = true;
    hasOut[x] = true;
  }
  for (int i = 1; i <= n; ++i) {
    if (!hasIn[i] && hasOut[i]) {
      first.push_back(i);
      dfs(i);
    }
  }
  cout << first.size() << "\n";
  for (int i = 0; i < first.size(); ++i) {
    cout << first[i] << " " << second[i] << " " << cost[i] << "\n";
  }
  return 0;
}
