#include <bits/stdc++.h>
using namespace std;
void fast() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
}
vector<pair<long long, long long>> adj[1001];
long long vis[1001], in[1001], out[1001];
long long present[1001];
long long sink;
long long mn = INT_MAX;
long long dfs(long long node) {
  vis[node] = 1;
  if (out[node] == 0) sink = node;
  for (auto child : adj[node]) {
    mn = min(mn, child.second);
    if (!vis[child.first]) dfs(child.first);
  }
  return mn;
}
int main() {
  fast();
  long long t = 1;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    while (m--) {
      long long u, v, cost;
      cin >> u >> v >> cost;
      adj[u].push_back({v, cost});
      present[u] = 1, present[v] = 1;
      out[u]++;
      in[v]++;
    }
    long long count = 0;
    vector<pair<int, pair<long long, long long>>> myvec;
    for (long long i = 1; i <= n; i++) {
      if (!vis[i] && in[i] == 0 && present[i]) {
        sink = 0;
        mn = INT_MAX;
        int weight = dfs(i);
        myvec.push_back(make_pair(i, make_pair(sink, weight)));
        count++;
      }
    }
    cout << count << endl;
    for (int i = 0; i < count; i++) {
      cout << myvec[i].first << " " << myvec[i].second.first << " "
           << myvec[i].second.second << endl;
    }
  }
  return 0;
}
