#include <bits/stdc++.h>
using namespace std;
long long e[1001][1001], n, p;
bool v[1001];
long long getnext(long long frm) {
  long long i;
  for (i = n; i > 0; i--) {
    if (e[frm][i]) break;
  }
  return i;
}
long long getbefo(long long to) {
  long long i;
  for (i = n; i > 0; i--) {
    if (e[i][to]) break;
  }
  return i;
}
int main() {
  vector<pair<int, pair<int, int> > > res;
  cin >> n >> p;
  for (long long i = 0; i < p; i++) {
    long long f, t;
    cin >> f >> t;
    cin >> e[f][t];
  }
  for (long long i = 1; i <= n; i++) {
    if (v[i]) continue;
    if (getbefo(i)) continue;
    v[i] = true;
    if (!getnext(i)) continue;
    long long now = i, next, mini = 9999999, flg = 0;
    while (next = getnext(now)) {
      if (v[next] == true) {
        flg = 1;
        break;
      }
      v[next] = true;
      mini = min(mini, e[now][next]);
      now = next;
    }
    if (flg) continue;
    res.push_back(make_pair(i, make_pair(now, mini)));
  }
  sort(res.begin(), res.end());
  cout << ((long long)res.size()) << endl;
  for (long long i = 0; i < ((long long)res.size()); i++) {
    cout << res[i].first << " " << res[i].second.first << " "
         << res[i].second.second << endl;
  }
  return 0;
}
