#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:255000000")
bool firstout = 1;
template <class T>
void minn(T &a, T b) {
  if (b < a) a = b;
}
template <class T>
void maxx(T &a, T b) {
  if (a < b) a = b;
}
int n, m;
int A[1012];
bool B[1012];
int D[1012];
int main() {
  int i, j, k;
  char c;
  int a, d;
  int ts;
  for (ts = 1; scanf("%"
                     "d",
                     &(n)) > 0;
       ++ts) {
    for (i = (0); i < (n); ++i) B[i] = 0, A[i] = -1;
    scanf(
        "%"
        "d",
        &(m));
    for (k = (0); k < (m); ++k) {
      scanf(
          "%"
          "d",
          &(i));
      scanf(
          "%"
          "d",
          &(j));
      scanf(
          "%"
          "d",
          &(a));
      --i;
      --j;
      A[i] = j;
      B[j] = 1;
      D[i] = a;
    }
    int res = 0;
    for (i = (0); i < (n); ++i)
      if (!B[i] && A[i] != -1) ++res;
    printf(
        "%"
        "d",
        (res));
    printf("\n"), firstout = 1;
    for (i = (0); i < (n); ++i)
      if (!B[i] && A[i] != -1) {
        printf((firstout) ? "%"
                            "d"
                          : " %"
                            "d",
               (i + 1)),
            firstout = 0;
        res = 1012345678;
        for (j = i; A[j] != -1; j = A[j]) minn(res, D[j]);
        printf((firstout) ? "%"
                            "d"
                          : " %"
                            "d",
               (j + 1)),
            firstout = 0;
        printf((firstout) ? "%"
                            "d"
                          : " %"
                            "d",
               (res)),
            firstout = 0;
        printf("\n"), firstout = 1;
      }
  }
  return 0;
}
