#include <bits/stdc++.h>
using namespace std;
long long M = 1e9 + 7;
const long long N = 2e5 + 10;
const long long IM = 1e15 + 37;
const long long PI = 3.14159265;
void PV(vector<long long> v) {
  for (long long i = 0; i < v.size(); i++) cout << v[i] << " ";
  cout << "\n";
}
void PA(long long v[], long long n, long long x = 0) {
  for (long long i = x; i < n + x; i++) cout << v[i] << ' ';
  cout << "\n";
}
void IN(long long a[], long long n, long long x = 0) {
  for (long long i = x; i < n + x; i++) cin >> a[i];
}
inline void PP(long long n) { cout << n << " "; }
inline void PP(long long n, long long m) { cout << n << " " << m << "\n"; }
inline void PP(long long n, long long m, long long q) {
  cout << n << " " << m << " " << q << "\n";
}
inline void PP(long long n, long long m, long long q, long long u) {
  cout << n << " " << m << " " << q << " " << u << "\n";
}
inline void op() {}
long long n, m, vis[1000 + 50];
vector<pair<long long, long long>> v[N];
vector<tuple<long long, long long, long long>> ans;
map<long long, long long> in;
long long s;
void dfs(long long x, long long l) {
  vis[x]++;
  for (auto it : v[x]) {
    if (v[it.first].size() == 0) {
      ans.push_back({s, it.first, min(l, it.second)});
      return;
    } else
      dfs(it.first, min(l, it.second));
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  op();
  long long i, j, x, y, u, k, l;
  {
    i = j = x = y = u = k = l = 0;
    cin >> n >> m;
    for (i = 0; i < m; i++) {
      cin >> x >> y >> k;
      v[x].push_back({y, k});
      in[y]++;
    }
    for (i = 1; i <= n; i++) {
      if (vis[i] == 0 && in[i] == 0) {
        s = i;
        dfs(i, IM);
      }
    }
    cout << (ans.size()) << "\n";
    for (i = 0; i < ans.size(); i++) {
      x = get<0>(ans[i]);
      y = get<1>(ans[i]);
      l = get<2>(ans[i]);
      PP(x, y, l);
    }
  }
  return 0;
}
