#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 * 1000 * 1000;
class point {
 public:
  int id1, id2, val;
};
bool operator<(const point &a, const point &b) {
  if (a.id1 < b.id1) return true;
  return false;
}
vector<point> ans;
vector<int> a[1001], cost[1001];
int deg[10001];
int n, m, i, j, x, y, z;
void dfs(int j, int s) {
  if ((a[j].size() == 0) && (deg[j] > 0)) {
    point p;
    p.id1 = i;
    p.id2 = j;
    p.val = s;
    ans.push_back(p);
  }
  int t;
  for (t = 0; t < a[j].size(); t++) dfs(a[j][t], min(s, cost[j][t]));
}
int main() {
  cin >> n >> m;
  for (i = 1; i <= m; i++) {
    cin >> x >> y >> z;
    a[x].push_back(y);
    deg[y]++;
    cost[x].push_back(z);
  }
  for (i = 1; i <= n; i++)
    if (deg[i] == 0) dfs(i, maxn);
  sort(ans.begin(), ans.end());
  cout << ans.size() << endl;
  for (i = 0; i < ans.size(); i++)
    cout << ans[i].id1 << " " << ans[i].id2 << " " << ans[i].val << endl;
  return 0;
}
