#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > adj_m;
vector<vector<pair<int, int> > > r_adj;
vector<bool> visit;
struct node {
  int a, b, c;
  node(int x, int y, int z) {
    a = x;
    b = y;
    c = z;
  }
  void print() { cout << a << " " << b << " " << c << endl; }
};
vector<node> ans;
void dfs(int root, int x, int d) {
  visit[x] = true;
  for (int i = 0; i < adj_m[x].size(); i++) {
    if (visit[adj_m[x][i].first] == false)
      dfs(root, adj_m[x][i].first, min(adj_m[x][i].second, d));
  }
  if (adj_m[x].size() == 0) {
    ans.push_back(node(root + 1, x + 1, d));
  }
}
int main() {
  int n, p;
  cin >> n >> p;
  adj_m.resize(n);
  r_adj.resize(n);
  visit.resize(n);
  for (int i = 0; i < p; i++) {
    int a, b, d;
    cin >> a >> b >> d;
    adj_m[a - 1].push_back(pair<int, int>(b - 1, d));
    r_adj[b - 1].push_back(pair<int, int>(a - 1, d));
  }
  vector<int> tanks;
  vector<int> taps;
  for (int i = 0; i < n; i++) {
    if (adj_m[i].size() == 0 && r_adj[i].size() > 0) {
      taps.push_back(i);
    }
    if (r_adj[i].size() == 0 && adj_m[i].size() > 0) {
      tanks.push_back(i);
    }
  }
  for (int i = 0; i < tanks.size(); i++) {
    dfs(tanks[i], tanks[i], 1000000);
  }
  cout << ans.size() << endl;
  for (int i = 0; i < ans.size(); i++) {
    ans[i].print();
  }
}
