#include <bits/stdc++.h>
using namespace std;
long long b[1001][1001], vis[1001], ans[1001][3], tap[1001], tank[1001];
vector<long long> adj[1001];
long long q = 0;
void dfs(long long v, long long mik, long long ver) {
  vis[v] = 1;
  for (long long i = 0; i < adj[v].size(); i++) {
    long long u = adj[v][i];
    if (vis[u] == 0) {
      dfs(u, min(mik, b[v][u]), ver);
    }
  }
  if (tap[v] == 1 && tank[v] == 0) {
    ans[q][0] = ver;
    ans[q][1] = v;
    ans[q][2] = mik;
    q++;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n, m, x, y, z;
  cin >> n >> m;
  for (long long i = 0; i < m; i++) {
    cin >> x >> y >> z;
    b[x][y] = z;
    tank[x]++;
    tap[y]++;
    adj[x].push_back(y);
  }
  for (long long i = 1; i <= n; i++) {
    if (tank[i] == 1 && tap[i] == 0) dfs(i, 100000000, i);
    for (long long j = 1; j <= n; j++) vis[j] = 0;
  }
  cout << q << endl;
  for (long long i = 0; i < q; i++)
    cout << ans[i][0] << " " << ans[i][1] << " " << ans[i][2] << endl;
  return 0;
}
