#include <bits/stdc++.h>
using namespace std;
const int inf_int = 2000000000;
vector<pair<int, int> > g[2000];
vector<int> cnt_in(2000, 0), cnt_out(2000, 0);
int p1 = -1;
int mn = inf_int;
vector<bool> used(2000, false);
void dfs(int v) {
  used[v] = true;
  if (cnt_out[v] == 0) {
    p1 = v;
    return;
  }
  for (int i = 0; i < g[v].size(); i++) {
    int to = g[v][i].first;
    int len = g[v][i].second;
    if (used[to] == false) {
      mn = min(mn, len);
      dfs(to);
    }
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int a, b, w;
    cin >> a >> b >> w;
    cnt_in[b]++;
    cnt_out[a]++;
    g[a].push_back({b, w});
  }
  vector<pair<int, int> > ans;
  vector<int> len;
  for (int i = 1; i <= n; i++) {
    if (cnt_in[i] == 0 && cnt_out[i] == 1) {
      mn = inf_int;
      dfs(i);
      if (p1 == -1) continue;
      ans.push_back({i, p1});
      len.push_back(mn);
    }
  }
  cout << ans.size() << "\n";
  for (int i = 0; i < ans.size(); i++) {
    cout << ans[i].first << " " << ans[i].second << " " << len[i] << "\n";
  }
  return 0;
}
