#include <bits/stdc++.h>
using namespace std;
vector<int> p[1010];
map<pair<int, int>, int> mp;
bool vis[1010];
pair<int, int> ANS;
int last_id;
int indeg[1010];
int outdeg[1010];
vector<pair<int, pair<int, int> > > ans;
pair<int, int> dfs(int n) {
  pair<int, int> ret;
  if (p[n].size() > 0) {
    ret = dfs(p[n][0]);
    ret.second = min(ret.second, mp[make_pair(n, p[n][0])]);
  } else {
    ret.first = n;
    ret.second = 10000000;
  }
  return ret;
}
int main() {
  int n, t;
  cin >> n >> t;
  while (t--) {
    int x, y, cap;
    cin >> x >> y >> cap;
    p[x].push_back(y);
    mp[make_pair(x, y)] = cap;
    indeg[y]++;
    outdeg[x]++;
  }
  vector<int> node;
  for (int i = 1; i <= n; i++) {
    if (outdeg[i] == 1 && indeg[i] == 0) node.push_back(i);
  }
  sort(node.begin(), node.end());
  for (int i = 0; i < node.size(); i++) {
    ANS = dfs(node[i]);
    ans.push_back(make_pair(node[i], make_pair(ANS.second, ANS.first)));
  }
  if (ans.size() == 0) {
    cout << 0;
    return 0;
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++) {
    cout << ans[i].first << " " << ans[i].second.second << " "
         << ans[i].second.first << endl;
  }
  return 0;
}
