#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > grph[1100];
vector<pair<pair<int, int>, int> > ans;
bool indeg[1100];
void solve(int src, int u, int cmin) {
  if (grph[u].size() == 0) {
    if (src != u) ans.push_back(make_pair(make_pair(src, u), cmin));
    return;
  }
  for (int i = 0; i < grph[u].size(); i++) {
    int v = grph[u][i].first;
    int wt = grph[u][i].second;
    solve(src, v, min(cmin, wt));
  }
}
int main() {
  ios::sync_with_stdio(0);
  int n, m, u, v, wt;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    cin >> u >> v >> wt;
    grph[u].push_back(make_pair(v, wt));
    indeg[v] = 1;
  }
  for (int i = 1; i <= n; i++) {
    if (!indeg[i]) solve(i, i, 1e8);
  }
  cout << ans.size() << "\n";
  for (int i = 0; i < ans.size(); i++)
    cout << ans[i].first.first << " " << ans[i].first.second << " "
         << ans[i].second << "\n";
  return 0;
}
