#include <bits/stdc++.h>
using namespace std;
int n, p, x, y, d;
int in[1005], out[1005];
vector<pair<int, int> > vec[1005];
vector<pair<pair<int, int>, int> > ans;
int dfs(int start) {
  for (int i = 0; i < vec[start].size(); i++) {
    d = min(d, vec[start][i].second);
    if (in[vec[start][i].first] == 1 && out[vec[start][i].first] == 1) {
      return dfs(vec[start][i].first);
    }
    if (in[vec[start][i].first] == 1 && out[vec[start][i].first] == 0) {
      return vec[start][i].first;
    }
  }
}
int main() {
  cin >> n >> p;
  for (int i = 0; i < p; i++) {
    cin >> x >> y >> d;
    out[x] = 1, in[y] = 1;
    vec[x].push_back(make_pair(y, d));
  }
  for (int i = 1; i <= n; i++) {
    if (out[i] == 1 && in[i] == 0) {
      d = 1000006;
      int flag = dfs(i);
      ans.push_back(make_pair(make_pair(i, flag), d));
    }
  }
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++)
    cout << ans[i].first.first << " " << ans[i].first.second << " "
         << ans[i].second << endl;
  return 0;
}
