#include <bits/stdc++.h>
using namespace std;
long long temp = 0, r, ans = 0, l, z, w, k = 0, m1 = 0, e, p, q, k1 = 0, k2 = 0,
          d = 0, a = 0, b = 0, s = 0, x, y, min1 = 1000000010, max1 = 0, m = 0,
          c = 0, t = 0, i, n, c1 = 0, tot = 0, t1, k4 = 0, c2 = 0, j = 0,
          k3 = 0;
char ch, ch1, ch2;
string s2, s3;
const long long N = 5000010;
vector<long long> v(N, 0), v1(N, 0);
vector<pair<long long, long long>> graph[N];
long long find(long long k) {
  if (v[k] != k) v[k] = find(v[k]);
  return v[k];
}
signed main() {
  cin >> n >> m;
  if (m == 0) {
    cout << 0;
    return 0;
  }
  m1 = 1000000007;
  set<long long> s4;
  for (i = 1; i <= n; i++) v[i] = i;
  vector<pair<long long, pair<long long, long long>>> v2;
  for (long long i = 0; i < m; i++) {
    cin >> a >> b >> c;
    v1[a] = 1, v1[b] = 1;
    graph[a].push_back({b, c});
    v[find(b)] = find(a);
  }
  for (long long i = 1; i < n + 1; i++) {
    if (v1[i]) s4.insert(v[find(i)]);
  }
  for (auto it : s4) {
    m1 = 1000000007, k2 = 0;
    for (i = 1; i <= n; i++) {
      if (v[find(i)] == it) {
        if (graph[i].size() != 0) m1 = min(m1, graph[i][0].second);
        if (graph[i].size() == 0) {
          k2 = i;
        }
      }
    }
    if (k2) v2.push_back(make_pair(it, make_pair(k2, m1)));
  }
  cout << ((long long)(v2).size()) << "\n";
  for (long long i = 0; i < ((long long)(v2).size()); i++)
    cout << v2[i].first << " " << v2[i].second.first << " "
         << v2[i].second.second << "\n";
}
