#include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
  cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
  const char* comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
const int N = 1e3 + 5;
int n, p;
int indeg[N], outdeg[N];
vector<pair<int, int> > adj[N];
vector<pair<int, pair<int, int> > > ans;
set<int> tanks, taps;
int src;
int vis[N];
void dfs(int u, int minn) {
  vis[u] = 1;
  for (auto p : adj[u]) {
    minn = min(minn, p.second);
    if (taps.find(p.first) != taps.end()) {
      ans.push_back({src, {p.first, minn}});
    }
    if (!vis[p.first]) dfs(p.first, minn);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  cin >> n >> p;
  for (int i = 1; i <= p; i++) {
    int a, b, d;
    cin >> a >> b >> d;
    outdeg[a]++;
    indeg[b]++;
    adj[a].push_back({b, d});
  }
  for (int i = 1; i <= n; i++) {
    if (indeg[i] == 0) {
      tanks.insert(i);
    }
    if (outdeg[i] == 0) {
      taps.insert(i);
    }
  }
  for (auto i : tanks) {
    src = i;
    memset(vis, 0, sizeof vis);
    dfs(i, INT_MAX);
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << "\n";
  for (auto ppp : ans) {
    cout << ppp.first << " " << ppp.second.first << " " << ppp.second.second
         << "\n";
  }
  return 0;
}
