#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int N, P;
vector<pair<int, int> > forw[MAXN], back[MAXN];
bool vis[MAXN];
vector<pair<pair<int, int>, int> > ans;
int main() {
  cin >> N >> P;
  for (int a, b, c, i = 0; i < P; i++) {
    cin >> a >> b >> c;
    forw[a].push_back(make_pair(b, c));
    back[b].push_back(make_pair(a, c));
  }
  for (int i = 1; i <= N; i++) {
    if (vis[i]) {
      continue;
    }
    if (back[i].empty() && !forw[i].empty()) {
      vis[i] = true;
      int v = i;
      int d = (1 << 27);
      while (!forw[v].empty()) {
        d = min(d, forw[v][0].second);
        v = forw[v][0].first;
      }
      ans.push_back(make_pair(make_pair(i, v), d));
    }
  }
  cout << ((int)ans.size()) << endl;
  sort(ans.begin(), ans.end());
  for (int i = 0; i < (int)ans.size(); i++) {
    cout << ans[i].first.first << " " << ans[i].first.second << " "
         << ans[i].second << endl;
  }
  return 0;
}
