#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > arr(1010);
int indegree[1010];
int main() {
  int n, p, i, j;
  cin >> n >> p;
  memset(indegree, 0, sizeof(int) * (n + 1));
  for (int i = 0; i < p; i += 1) {
    int a, b, d;
    cin >> a >> b >> d;
    arr[a].push_back(make_pair(b, d));
    indegree[b]++;
  }
  stack<int> st1;
  stack<int> st2;
  int vis[n];
  memset(vis, 0, sizeof(int) * n);
  j = 0;
  for (i = 1; i <= n; i++) {
    if (indegree[i] == 0 && arr[i].size() > 0) j++;
  }
  cout << j << "\n";
  for (i = 1; i <= n; i++) {
    if (indegree[i] == 0) {
      int dia = INT_MAX;
      int k = i;
      while (true) {
        if (arr[k].size() == 0) break;
        dia = min(dia, arr[k][0].second);
        k = arr[k][0].first;
      }
      if (k != i) cout << i << " " << k << " " << dia << "\n";
    }
  }
}
