#include <bits/stdc++.h>
using namespace std;
int cnt1[2000], cnt2[2000], minn[2000], cnt[2000];
int a[2000][15];
int n, m, p, temp, x, y, z;
bool flag;
void dfs(int u) {
  if (a[u][1] != -1) {
    if (temp > a[u][2]) temp = a[u][2];
    dfs(a[u][1]);
  }
  if (flag == true && cnt1[m] != u) {
    cnt2[m] = u;
    minn[m] = temp;
    flag = false;
  }
  return;
}
int main() {
  cin >> n >> p;
  for (int i = 1; i <= n; i++) {
    a[i][1] = -1;
  }
  memset(cnt, 0, sizeof(cnt));
  memset(cnt1, 0, sizeof(cnt1));
  memset(cnt2, 0, sizeof(cnt2));
  for (int i = 1; i <= p; i++) {
    cin >> x >> y >> z;
    a[x][1] = y;
    a[x][2] = z;
    cnt[y]++;
  }
  m = -1;
  for (int i = 1; i <= n; i++) {
    if (cnt[i] == 0) {
      m++;
      flag = true;
      temp = 1 << 30;
      cnt1[m] = i;
      dfs(i);
      if (cnt2[m] == 0) m--;
    }
  }
  cout << m + 1 << endl;
  for (int i = 0; i <= m; i++) {
    if (cnt2[i] != 0)
      cout << cnt1[i] << " " << cnt2[i] << " " << minn[i] << endl;
  }
  return 0;
}
