#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 10;
int n, m, out[maxn], cost[maxn], MIN, INF = 10000000;
bool in[maxn];
vector<pair<pair<int, int>, int> > ans;
int dfs(int v) {
  if (out[v] == -1) return v;
  MIN = min(MIN, cost[v]);
  return dfs(out[v]);
}
int main() {
  memset(out, -1, sizeof out);
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int v, u, w;
    cin >> v >> u >> w;
    v--;
    u--;
    out[v] = u;
    cost[v] = w;
    in[u] = true;
  }
  for (int i = 0; i < n; i++)
    if (!in[i] && out[i] != -1) {
      MIN = INF;
      int u = dfs(i);
      ans.push_back(make_pair(pair<int, int>(i, u), MIN));
    }
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++)
    cout << ans[i].first.first + 1 << ' ' << ans[i].first.second + 1 << ' '
         << ans[i].second << endl;
  return 0;
}
