#include <bits/stdc++.h>
using namespace std;
long long bigmod(long long b, long long p, long long md) {
  if (p == 0) return 1;
  if (p % 2 == 1) {
    return ((b % md) * bigmod(b, p - 1, md)) % md;
  } else {
    long long y = bigmod(b, p / 2, md);
    return (y * y) % md;
  }
}
int in[20000];
int out[20000];
vector<int> v[20000];
vector<int> e[20000];
bool vis[20000];
int ans = 1e9;
int tap = 0;
int flag;
void dfs(int s) {
  vis[s] = true;
  for (int i = 0; i < v[s].size(); i++) {
    int now = v[s][i];
    if (vis[now] == false) {
      ans = min(ans, e[s][i]);
      if (in[now] == 1 && out[now] == 0) {
        flag = 1;
        tap = now;
      }
      dfs(now);
    }
  }
}
int main() {
  int n, p;
  cin >> n >> p;
  for (int i = 0; i < p; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    v[a].push_back(b);
    e[a].push_back(c);
    in[b]++;
    out[a]++;
  }
  vector<int> tank;
  for (int i = 1; i <= n; i++) {
    if (out[i] == 1 && in[i] == 0) {
      tank.push_back(i);
    }
  }
  vector<pair<int, pair<int, int> > > res;
  for (int i = 0; i < tank.size(); i++) {
    int t = tank[i];
    flag = 0;
    ans = 1e9;
    dfs(t);
    if (flag) {
      res.push_back(make_pair(t, make_pair(tap, ans)));
    }
  }
  sort(res.begin(), res.end());
  cout << res.size() << endl;
  for (int i = 0; i < res.size(); i++) {
    cout << res[i].first << " " << res[i].second.first << " "
         << res[i].second.second << endl;
  }
  return 0;
}
