#include <bits/stdc++.h>
using namespace std;
int a[1001][3] = {0};
int b[1001] = {0};
int c[1001] = {0};
vector<int> a1, a2, a3;
int main() {
  int n, m, i, x, y, z;
  int ans, t = 0;
  scanf("%d%d", &n, &m);
  for (i = 0; i < m; i++) {
    scanf("%d%d%d", &x, &y, &z);
    a[x][0] = y;
    a[x][1] = z;
    b[x]++;
    c[y]++;
  }
  for (i = 1; i <= n; i++) {
    if (b[i] == 1 && c[i] == 0) {
      x = i;
      ans = 1000001;
      do {
        if (a[x][0] > 0) {
          ans = min(ans, a[x][1]);
          x = a[x][0];
        } else
          break;
      } while (1);
      a1.push_back(i);
      a2.push_back(x);
      a3.push_back(ans);
    }
  }
  printf("%d\n", a1.size());
  for (i = 0; i < a1.size(); i++) printf("%d %d %d\n", a1[i], a2[i], a3[i]);
  return 0;
}
