#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<long long int, long long int> > > adj(2005);
vector<vector<long long int> > adi(2005);
int vis[2005], in[2005], out[2005];
vector<long long int> v;
long long int minn;
void dfs(int u) {
  if (vis[u] == 1) return;
  vis[u] = 1;
  v.push_back(u);
  for (int i = 0; i < adj[u].size(); i++) {
    pair<long long int, long long int> pp = adj[u][i];
    if (vis[pp.first] == 0) {
      minn = min(minn, pp.second);
      dfs(pp.first);
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long int n, m, a, b, c;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    cin >> a >> b >> c;
    a--;
    b--;
    adj[a].push_back(pair<long long int, long long int>(b, c));
    out[a]++;
    in[b]++;
  }
  c = 0;
  for (int i = 0; i < n; i++) {
    v.clear();
    minn = 9999999999;
    if (!vis[i] && in[i] == 0) {
      dfs(i);
      if (v.size() > 1) {
        adi[c].push_back(v[0]);
        adi[c].push_back(v[v.size() - 1]);
        adi[c].push_back(minn);
        c++;
      }
    }
  }
  cout << c << endl;
  for (int i = 0; i < c; i++)
    cout << adi[i][0] + 1 << " " << adi[i][1] + 1 << " " << adi[i][2] << endl;
  return 0;
}
