#include <bits/stdc++.h>
int i, j, mn, x, y, c, n, k, a[1010][1010], p[1010], d[1010], e[1010];
bool v[1010];
using namespace std;
int main() {
  for (i = 0; i < 1010; i++) v[i] = false;
  for (i = 0; i < 1010; i++)
    for (j = 0; j < 1010; j++) a[i][j] = 0;
  cin >> n >> k;
  for (i = 0; i < k; i++) {
    cin >> x >> y >> c;
    a[y - 1][x - 1] = c;
  }
  k = 0;
  for (i = 0; i < n; i++)
    if (!v[i]) {
      c = 0;
      for (j = 0; j < n; j++) c += a[i][j];
      if (c == 0) {
        x = i;
        mn = 1000010;
        while (!v[x]) {
          y = x;
          v[x] = true;
          for (j = 0; j < n; j++)
            if (a[j][x] > 0) {
              if (a[j][x] < mn) mn = a[j][x];
              x = j;
              break;
            }
          if (y == x) break;
        }
        if (x != i) {
          p[k] = i + 1;
          d[k] = x + 1;
          e[k] = mn;
          k++;
        }
      }
    }
  cout << k << endl;
  for (i = 0; i < k; i++) cout << p[i] << ' ' << d[i] << ' ' << e[i] << endl;
}
