#include <bits/stdc++.h>
using namespace std;
int A[1005];
int B[1005];
int C[1005];
pair<int, int> dfs(int idx, int cap) {
  if (A[idx] != -1) {
    return dfs(A[idx], min(cap, C[idx]));
  }
  return make_pair(idx, cap);
}
int main(int argc, char** argv) {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < 1005; i++) A[i] = B[i] = -1;
  for (int i = 0; i < 1005; i++) C[i] = 0;
  int a, b, c;
  for (int i = 0; i < m; i++) {
    scanf("%d%d%d", &a, &b, &c);
    A[a - 1] = b - 1;
    B[b - 1] = a - 1;
    C[a - 1] = c;
  }
  vector<pair<int, pair<int, int> > > Ans;
  for (int i = 0; i < n; i++) {
    if (A[i] >= 0 && B[i] == -1) {
      pair<int, int> ans;
      ans = dfs(i, 1000000000);
      Ans.push_back(make_pair(i, ans));
    }
  }
  printf("%d\n", ((int)Ans.size()));
  for (int i = 0; i < ((int)Ans.size()); i++) {
    printf("%d %d %d\n", Ans[i].first + 1, Ans[i].second.first + 1,
           Ans[i].second.second);
  }
  return 0;
}
