#include <bits/stdc++.h>
using namespace std;
unordered_map<int, vector<pair<int, int> > > g;
unordered_map<int, bool> visited;
vector<pair<pair<int, int>, int> > v;
map<int, int> cnt;
void dfsutil(int i) {
  visited[i] = true;
  int s = i, m = INT_MAX;
  while (g[i].size()) {
    m = min(m, g[i][0].second);
    i = g[i][0].first;
    visited[i] = true;
    if (i == s) break;
  }
  if (i != s) v.push_back({{s, i}, m});
}
void dfs(int n) {
  for (auto it : cnt) {
    if (it.second == 1) {
      if (!visited[it.first]) dfsutil(it.first);
    }
  }
  for (int i = 1; i <= n; ++i) {
    if (!visited[i]) dfsutil(i);
  }
}
int main() {
  int n, p, a, b, d;
  cin >> n >> p;
  while (p--) {
    cin >> a >> b >> d;
    cnt[a]++;
    cnt[b]++;
    g[a].push_back({b, d});
  }
  dfs(n);
  cout << v.size() << "\n";
  for (auto it : v) {
    cout << it.first.first << " " << it.first.second << " " << it.second
         << "\n";
  }
  return 0;
}
