#include <bits/stdc++.h>
using namespace std;
int in_degree[1001], out_degree[1001];
vector<pair<int, int> > E[1001];
pair<int, int> dfs(int n, int p, int ans) {
  if (out_degree[n] == 0) return make_pair(n, ans);
  for (int i = 0; i < E[n].size(); i++) {
    int v = E[n][i].first;
    int c = E[n][i].second;
    if (v == p) continue;
    return dfs(v, n, min(ans, c));
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  int n, m;
  while (cin >> n >> m) {
    for (int i = 1; i <= n; i++) {
      E[i].clear();
      in_degree[i] = out_degree[i] = 0;
    }
    for (int i = 1; i <= m; i++) {
      int s, d, c;
      cin >> s >> d >> c;
      E[s].push_back(make_pair(d, c));
      E[d].push_back(make_pair(s, c));
      in_degree[d]++;
      out_degree[s]++;
    }
    vector<pair<int, pair<int, int> > > ans;
    int curComponent = 0;
    for (int i = 1; i <= n; i++) {
      if (out_degree[i] == 1 && in_degree[i] == 0) {
        pair<int, int> ret = dfs(i, -1, (1 << 30));
        ans.push_back(make_pair(i, make_pair(ret.first, ret.second)));
        curComponent++;
      }
    }
    cout << ans.size() << endl;
    for (int i = 0; i < ans.size(); i++)
      cout << ans[i].first << " " << ans[i].second.first << " "
           << ans[i].second.second << endl;
  }
  return 0;
}
