#include <bits/stdc++.h>
using namespace std;
stringstream ss;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};
int n, m;
struct Dorm {
 public:
  int to, dia, from;
  bool checked;
  Dorm() {
    to = 0;
    dia = 0;
    from = 0;
    checked = false;
  }
};
int main() {
  cin >> n >> m;
  Dorm d[1001];
  int a, b, c;
  for (int i = (int)(0); i < (int)(m); i++) {
    cin >> a >> b >> c;
    d[a].to = b;
    d[b].from = a;
    d[a].dia = c;
  }
  int start, mindia, pos;
  vector<int> ans;
  for (int i = (int)(1); i < (int)(n + 1); i++) {
    if (d[i].checked) continue;
    d[i].checked = true;
    start = i;
    mindia = d[i].dia;
    pos = i;
    while (1) {
      if (d[pos].to == start) {
        d[pos].checked = true;
        break;
      }
      if (d[pos].to == 0) {
        d[pos].checked = true;
        if (start == pos) break;
        if (d[start].from != 0) break;
        ans.push_back(start);
        ans.push_back(pos);
        ans.push_back(mindia);
        break;
      }
      d[pos].checked = true;
      mindia = min(mindia, d[pos].dia);
      pos = d[pos].to;
    }
  }
  cout << ans.size() / 3 << endl;
  for (int i = (int)(0); i < (int)(ans.size() / 3); i++) {
    int ii = i * 3;
    cout << ans[ii] << " " << ans[ii + 1] << " " << ans[ii + 2] << endl;
  }
}
