#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int nax = 1e6 + 10;
long long int i, j, x, y, k, f, z, cnt;
vector<vector<long long int>> a(100005);
map<long long int, map<long long int, long long int>> m;
bool visited[100005];
long long int pre;
int dfs(long long int u, long long int &Min) {
  visited[u] = true;
  vector<long long int>::iterator it;
  for (it = a[u].begin(); it != a[u].end(); it++) {
    if (!visited[*it]) {
      Min = min(m[u][*it], Min);
      pre = *it;
      dfs(*it, Min);
    }
  }
  return pre;
}
int main() {
  long long int t = 1;
  while (t--) {
    long long int n, p;
    cin >> n >> p;
    map<long long int, long long int> reach;
    for (i = 0; i < p; i++) {
      cin >> x >> y >> z;
      a[x].push_back(y);
      reach[y] = 1;
      m[x][y] = z;
    }
    memset(visited, false, sizeof(visited));
    vector<pair<pair<long long int, long long int>, long long int>> ans;
    for (i = 1; i <= n; i++) {
      long long int Min = LLONG_MAX;
      if (!visited[i] && reach[i] == 0 && a[i].size() != 0) {
        long long int cnt = dfs(i, Min);
        if (m[cnt][i] == 0) {
          ans.push_back(make_pair(make_pair(i, cnt), Min));
        }
      }
    }
    cout << ans.size() << endl;
    for (i = 0; i < ans.size(); i++) {
      cout << ans[i].first.first << " " << ans[i].first.second << " "
           << ans[i].second << endl;
    }
  }
  return 0;
}
