#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
class edge {
 public:
  edge(int _to = 0, int _d = 0) : to(_to), d(_d) {}
  int to, d;
};
class tri {
 public:
  tri(int _a = 0, int _b = 0, int _c = 0) : a(_a), b(_b), c(_c) {}
  int a, b, c;
};
vector<edge> g;
vector<int> is_root, is_leaf;
int main() {
  int n, m;
  cin >> n >> m;
  g = vector<edge>(n);
  is_root = vector<int>(n, 1);
  is_leaf = vector<int>(n, 1);
  int a, b, d;
  for (int i = 0; i < m; i++) {
    scanf("%d%d%d", &a, &b, &d);
    a--;
    b--;
    g[a] = edge(b, d);
    is_root[b] = 0;
    is_leaf[a] = 0;
  }
  vector<tri> res;
  for (int i = 0; i < n; i++) {
    if (is_root[i]) {
      int d = 1000000000;
      int ver = i;
      while (!is_leaf[ver]) {
        d = min(d, g[ver].d);
        ver = g[ver].to;
      }
      if (d < 1000000000) res.push_back(tri(i + 1, ver + 1, d));
    }
  }
  cout << res.size() << endl;
  for (int i = 0; i < res.size(); i++) {
    cout << res[i].a << " " << res[i].b << " " << res[i].c << endl;
  }
  return 0;
}
