#include <bits/stdc++.h>
using namespace std;
int b[1001], a[1001][1001];
vector<int> v[1001];
int m, c, n, p;
void dfs(int i) {
  if (v[i].size() > 0) {
    if (m > a[i][v[i][0]]) m = a[i][v[i][0]];
    dfs(v[i][0]);
  } else {
    c = i;
  }
}
int main() {
  int i, q = 0, t, u, d, j, k = 0;
  int dq[1001][3];
  cin >> n >> p;
  for (i = 1; i <= p; i++) {
    cin >> t >> u >> d;
    a[t][u] = d;
    v[t].push_back(u);
    b[u] = 1;
    q++;
  }
  if (q == n) {
    cout << "0";
    return 0;
  }
  for (i = 1; i <= n; i++) {
    if (b[i] != 1) {
      m = 1000001;
      c = 0;
      dfs(i);
      if (m != 1000001) {
        dq[k][0] = i;
        dq[k][1] = c;
        dq[k][2] = m;
        k++;
      }
    }
  }
  cout << k << "\n";
  for (i = 0; i < k; i++)
    cout << dq[i][0] << " " << dq[i][1] << " " << dq[i][2] << "\n";
  return 0;
}
