#include <bits/stdc++.h>
using namespace std;
int n, p;
int a[1001], b[1001], c[1001];
bool f1[1001], f2[1001];
vector<int> incoming, outcoming;
pair<int, int> s[1001];
int ans = 1000000;
int findout(int y) {
  for (int i = 0; i < outcoming.size(); i++)
    if (y == outcoming[i]) return y;
  for (int i = 0; i < p; i++) {
    if (a[i] == y) {
      ans = min(ans, c[i]);
      return findout(b[i]);
    }
  }
  return 0;
}
int main() {
  cin >> n >> p;
  for (int i = 0; i < p; i++) {
    cin >> a[i] >> b[i] >> c[i];
    f1[a[i]] = true;
    f2[b[i]] = true;
  }
  for (int i = 1; i <= n; i++) {
    if (!f1[i] && !f2[i]) continue;
    if (f1[i] && f2[i])
      continue;
    else if (!f2[i])
      incoming.push_back(i);
    else if (!f1[i])
      outcoming.push_back(i);
  }
  cout << incoming.size() << endl;
  for (int i = 0; i < incoming.size(); i++) {
    int uu = findout(incoming[i]);
    if (!uu) continue;
    cout << incoming[i] << " " << uu << " " << ans << endl;
    ans = 1000000;
  }
  return 0;
}
