#include <bits/stdc++.h>
using namespace std;
string name = "problem";
string infname = name + ".in";
string outfname = name + ".out";
vector<bool> used;
vector<vector<int> > g;
pair<int, int> dfs(int v) {
  pair<int, int> ans = make_pair(100000000, v);
  used[v] = true;
  for (int i = 0; i < g.size(); i++) {
    if (!used[i] && g[v][i] > 0) {
      pair<int, int> tans = dfs(i);
      ans.second = tans.second;
      ans.first = min(g[v][i], tans.first);
      break;
    }
  }
  return ans;
}
int main() {
  ifstream ifstr(infname.c_str());
  ofstream ofstr(outfname.c_str());
  istream &ifs = cin;
  ostream &ofs = cout;
  int n, p;
  ifs >> n >> p;
  g.resize(n, vector<int>(n, 0));
  vector<int> k(n, 0);
  for (int i = 0; i < p; i++) {
    int a, b, d;
    ifs >> a >> b >> d;
    k[a - 1]++;
    k[b - 1]--;
    g[a - 1][b - 1] = d;
  }
  used.resize(n, false);
  int c = 0;
  vector<int> tk, tp, d;
  for (int i = 0; i < n; i++) {
    int w = -1;
    for (int j = 0; j < n; j++) {
      if (!used[j] && k[j] == 1) {
        w = j;
        break;
      }
    }
    if (w == -1) break;
    pair<int, int> ans = dfs(w);
    c++;
    tk.push_back(w + 1);
    tp.push_back(ans.second + 1);
    d.push_back(ans.first);
  }
  ofs << c << endl;
  for (int i = 0; i < c; i++) {
    ofs << tk[i] << " " << tp[i] << " " << d[i] << endl;
  }
  return 0;
}
