#include <bits/stdc++.h>
using namespace std;
inline int nxt() {
  int a;
  scanf("%d", &a);
  return a;
}
inline long long gcd(long long a, long long b) {
  while (b) {
    a %= b;
    swap(a, b);
  }
  return a;
}
vector<pair<int, int> > g[1000];
pair<int, int> dfs(int v) {
  for (pair<int, int> t : g[v]) {
    pair<int, int> ret = dfs(t.first);
    ret.second = min(ret.second, t.second);
    return ret;
  }
  return make_pair(v, INT_MAX);
}
void solve() {
  int n = nxt();
  int m = nxt();
  int in_cnt[n];
  memset((in_cnt), 0, sizeof((in_cnt)));
  for (int i = 0; i < m; ++i) {
    int a = nxt() - 1;
    int b = nxt() - 1;
    int d = nxt();
    in_cnt[b]++;
    g[a].push_back(make_pair(b, d));
  }
  vector<pair<pair<int, int>, int> > ans;
  for (int i = 0; i < n; ++i) {
    if (in_cnt[i] == 0 && !g[i].empty()) {
      pair<int, int> ret = dfs(i);
      ans.push_back(make_pair(make_pair(i, ret.first), ret.second));
    }
  }
  cout << ans.size() << "\n";
  for (int i = 0; i < (int)ans.size(); ++i) {
    cout << ans[i].first.first + 1 << " " << ans[i].first.second + 1 << " "
         << ans[i].second << "\n";
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  solve();
  return 0;
}
