#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:200000000")
using namespace std;
const int INF = (int)1E9;
const long long INF64 = (long long)1E18;
const double EPS = 1E-9;
const double PI = acos((double)0) * 2;
const int MAXN = 1000;
int n, m, g[MAXN], w[MAXN];
bool has_in[MAXN];
bool read() {
  if (!(cin >> n >> m)) return false;
  memset(g, -1, sizeof g);
  memset(has_in, 0, sizeof has_in);
  for (int i = 0; i < int(m); ++i) {
    int x, y;
    cin >> x >> y;
    --x, --y;
    has_in[y] = true;
    g[x] = y;
    cin >> w[x];
  }
  return true;
}
void solve() {
  vector<pair<int, pair<int, int> > > res;
  for (int i = 0; i < int(n); ++i)
    if (!has_in[i] && g[i] != -1) {
      int j = i, ans = INF;
      while (g[j] != -1) {
        ans = min(ans, w[j]);
        j = g[j];
      }
      res.push_back(make_pair(i, make_pair(j, ans)));
    }
  printf("%d\n", res.size());
  for (int i = 0; i < int(res.size()); ++i)
    printf("%d %d %d\n", res[i].first + 1, res[i].second.first + 1,
           res[i].second.second);
}
int main() {
  if (read())
    solve();
  else
    throw;
}
