#include <bits/stdc++.h>
using namespace std;
int n, p, somVal;
long long minn;
bool found;
vector<int> vals(0), missing(0);
void recursive(int x, vector<vector<pair<int, long long>>> list) {
  if (found) return;
  int size = list[x].size();
  int i = 0;
  if (list[x].size() == 0) {
    found = true;
    somVal = x;
  }
  while (i < size && !found) {
    if (list[x][i].second < minn) minn = list[x][i].second;
    recursive(list[x][i].first, list);
    i++;
  }
  return;
}
int main() {
  cin >> n >> p;
  int a, b, d, value;
  bool val;
  vector<vector<pair<int, long long>>> list(n + 1);
  for (int i = 0; i < p; i++) {
    cin >> a >> b >> d;
    if (count(missing.begin(), missing.end(), a) == 0) missing.push_back(a);
    if (count(missing.begin(), missing.end(), b) == 0) missing.push_back(b);
    if (count(vals.begin(), vals.end(), b) == 0) vals.push_back(b);
    list[a].push_back(make_pair(b, d));
  }
  int t = missing.size() - vals.size();
  for (int i = 0; i < vals.size(); i++) {
    for (int j = 0; j < missing.size(); j++) {
      if (vals[i] == missing[j]) missing.erase(missing.begin() + j);
    }
  }
  cout << t << endl;
  sort(missing.begin(), missing.end());
  for (int i = 0; i < missing.size(); i++) {
    val = false, found = false;
    minn = list[missing[i]][0].second;
    if (list[missing[i]].size()) val = true;
    recursive(missing[i], list);
    val ? cout << missing[i] << " " << somVal << " " << minn << endl
        : cout << somVal << " " << missing[i] << " " << minn << endl;
  }
  return 0;
}
