#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, mod = 1000000007;
int n, p, a[N], b[N], c[N];
vector<pair<int, int> > G[N];
bool vs[N];
int in[N], out[N];
vector<pair<int, pair<int, int> > > res;
void DFS(int t, int raiz, int ma) {
  vs[t] = true;
  if (out[t] == 0) {
    if (t != raiz) {
      res.push_back(make_pair(raiz, make_pair(t, ma)));
      return;
    }
  } else {
    for (pair<int, int> v : G[t]) {
      if (!vs[v.first]) {
        DFS(v.first, raiz, min(ma, v.second));
      }
    }
  }
}
int main() {
  cin.tie(0);
  cout.tie(0);
  ios_base::sync_with_stdio();
  cin >> n >> p;
  for (int i = 0; i < p; i++) {
    cin >> a[i] >> b[i] >> c[i];
    out[a[i]]++;
    in[b[i]]++;
    G[a[i]].push_back(make_pair(b[i], c[i]));
  }
  for (int i = 1; i <= n; i++)
    if (in[i] == 0) {
      for (int j = 0; j <= n; j++) vs[j] = false;
      DFS(i, i, mod);
    }
  cout << ((int)res.size()) << "\n";
  sort(res.begin(), res.end());
  for (pair<int, pair<int, int> > k : res) {
    cout << k.first << " " << k.second.first << " " << k.second.second << "\n";
  }
  return 0;
}
