#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > v;
vector<int> vis(1000), ans;
vector<pair<int, int> > res;
int n, p, temp[1001][2] = {0};
bool dfs(int pos) {
  int k = pos;
  queue<int> q;
  vis[pos] = 1;
  q.push(pos);
  int m = 0;
  while (!q.empty()) {
    for (int i = 0; i < v[pos].size(); ++i) {
      if (!vis[v[pos][i].first]) {
        vis[v[pos][i].first] = 1;
        q.push(v[pos][i].first);
        if (m == 0)
          m = v[pos][i].second;
        else if (v[pos][i].second < m)
          m = v[pos][i].second;
      }
    }
    q.pop();
    if (!q.empty()) pos = q.front();
  }
  for (int i = 0; i < v[pos].size(); ++i) {
    if (v[pos][i].first == k) return 0;
  }
  if (m == 0)
    return 0;
  else {
    ans.push_back(m);
    res.push_back(make_pair(k, pos));
    return 1;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  int a, b, d, ctr = 0;
  cin >> n >> p;
  v.resize(n);
  for (int i = 0; i < p; i++) {
    cin >> a >> b >> d;
    a--;
    b--;
    temp[a][1]++;
    temp[b][0]++;
    v[a].push_back(make_pair(b, d));
  }
  for (int i = 0; i < n; i++) {
    if (vis[i] != 0) continue;
    if (temp[i][0] == 0)
      if (dfs(i)) ctr++;
  }
  cout << ctr << endl;
  for (int i = 0; i < ans.size(); i++)
    if (ans[i] != 0)
      cout << res[i].first + 1 << " " << res[i].second + 1 << " " << ans[i]
           << endl;
}
