#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > g;
vector<bool> used;
int dfs(int v, int &h_m) {
  used[v] = true;
  if (((int)g[v].size()) == 0) return v;
  for (int i(0); i <= (((int)g[v].size()) - 1); i++) {
    int to = g[v][i].first;
    int h = g[v][i].second;
    if (h_m > h) h_m = h;
    if (!used[to]) {
      return dfs(to, h_m);
    } else
      return -1;
  }
}
int main() {
  int n, p;
  scanf("%d%d", &n, &p);
  g.resize(n);
  bool is_in[1010], is_out[1010];
  memset(is_in, false, sizeof is_in);
  memset(is_out, false, sizeof is_out);
  for (int i(0); i <= (p - 1); i++) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    g[a - 1].push_back(make_pair(b - 1, c));
    is_in[b - 1] = true;
    is_out[a - 1] = true;
  }
  vector<int> need;
  for (int i(0); i <= (n - 1); i++)
    if (!is_in[i] && is_out[i]) need.push_back(i);
  vector<pair<pair<int, int>, int> > ans;
  used.assign(n, false);
  for (int i(0); i <= (((int)need.size()) - 1); i++) {
    int h_m = 2000000000;
    int last = dfs(need[i], h_m);
    if (last != -1) {
      ans.push_back(make_pair(make_pair(need[i], last), h_m));
    }
  }
  printf("%d\n", ((int)ans.size()));
  for (int i(0); i <= (((int)ans.size()) - 1); i++) {
    printf("%d %d %d\n", ans[i].first.first + 1, ans[i].first.second + 1,
           ans[i].second);
  }
  return 0;
}
