#include <bits/stdc++.h>
using namespace std;
static const double EPS = 1e-11;
const double pi = acos(-1);
int dx[] = {0, 1, 0, -1, 1, 1, -1, -1}, dy[] = {1, 0, -1, 0, 1, -1, 1, -1};
vector<pair<int, int> > G[1000];
bool nst[1000];
bool app[1000];
int main() {
  int n, p;
  cin >> n >> p;
  for (int i = 0; i < (int)(p); ++i) {
    int a, b, d;
    cin >> a >> b >> d;
    app[a - 1] = app[b - 1] = 1;
    G[a - 1].push_back(make_pair(b - 1, d));
    nst[b - 1] = 1;
  }
  vector<pair<int, pair<int, int> > > ans;
  for (int j = 0; j < (int)(n); ++j) {
    if (nst[j] || !app[j]) continue;
    int m = 1000000;
    int tp = j;
    while (!G[tp].empty()) {
      m = min(m, G[tp][0].second);
      tp = G[tp][0].first;
    }
    ans.push_back(make_pair(j + 1, make_pair(tp + 1, m)));
  }
  cout << (int(ans.size())) << endl;
  for (__typeof((ans).begin()) it = (ans).begin(); it != (ans).end(); ++it)
    cout << it->first << ' ' << it->second.first << ' ' << it->second.second
         << endl;
}
