#include <bits/stdc++.h>
using namespace std;
long long int poww(long long int x, long long int y) {
  if (y == 0) return 1;
  long long int second = poww(x, y / 2);
  second = (second * second);
  if (y % 2 == 1) second = (second * x);
  return second;
}
long long sumpows(long long a, long long k) {
  if (k == 0) return 0;
  if (k % 2 == 1) return a * (1 + sumpows(a, k - 1));
  long long half = sumpows(a, k / 2);
  return half * (1 + half - sumpows(a, k / 2 - 1));
}
struct cmp {
  bool operator()(const pair<int, int> &p1, const pair<int, int> &p2) const {
    if ((p1.second - p1.first + 1) == (p2.second - p2.first + 1)) {
      return p1.first < p2.first;
    }
    return (p1.second - p1.first + 1) > (p2.second - p2.first + 1);
  }
};
vector<pair<int, pair<int, int>>> res;
bitset<1001> vis;
vector<vector<pair<int, int>>> adj(1001), adj1(1001);
vector<int> second;
int mi;
void dfs(int u) {
  vis[u] = 1;
  second.push_back(u);
  for (auto &i : adj[u]) {
    if (!vis[i.first]) {
      mi = min(mi, i.second);
      dfs(i.first);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, p;
  cin >> n >> p;
  for (int i = 0; i < p; ++i) {
    int u, v, w;
    cin >> u >> v >> w;
    adj[u].push_back(make_pair(v, w));
    adj1[v].push_back(make_pair(u, w));
  }
  for (int i = 1; i <= n; ++i) {
    if (!vis[i] && adj1[i].size() == 0) {
      mi = int(1e7);
      second.clear();
      dfs(i);
      if (mi != int(1e7))
        res.push_back(make_pair(i, make_pair(second.back(), mi)));
    }
  }
  cout << res.size() << endl;
  for (auto &i : res) {
    cout << i.first << " " << i.second.first << " " << i.second.second << endl;
  }
  return 0;
}
