#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
vector<pair<int, int> > g[N];
vector<pair<pair<int, int>, int> > ans;
int in[N], out[N];
int n, m;
void process(int v) {
  int D = 1 << 30, start = v;
  while (!g[v].empty()) {
    D = min(D, g[v][0].second);
    v = g[v][0].first;
  }
  if (start != v) ans.push_back(make_pair(pair<int, int>(start, v), D));
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; i++) {
    int a, b, d;
    scanf("%d%d%d", &a, &b, &d);
    g[a].push_back(pair<int, int>(b, d));
    in[b]++;
    out[a]++;
  }
  for (int i = 1; i <= n; i++)
    if (!in[i]) process(i);
  sort(ans.begin(), ans.end());
  printf("%d\n", (int)ans.size());
  for (int i = 0; i < (int)ans.size(); i++)
    printf("%d %d %d\n", ans[i].first.first, ans[i].first.second,
           ans[i].second);
  return 0;
}
