#include <bits/stdc++.h>
using namespace std;
static const double EPS = 1e-8;
static const int INF = (1 << 29);
struct course {
  int tank, tap, amt;
  course(int tank, int tap, int amt) : tank(tank), tap(tap), amt(amt) {}
};
bool operator<(const course &e, const course &f) { return e.tank < f.tank; }
int main(void) {
  int n, p;
  cin >> n >> p;
  int out[1001];
  bool in[1001] = {};
  bool arv[1001] = {};
  int amount[1001];
  for (int i = 0; i < (int)(n); ++i) {
    out[i] = -1;
  }
  for (int i = 0; i < (int)(p); ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    a--;
    b--;
    out[a] = b;
    amount[a] = c;
    in[b] = true;
  }
  vector<course> ans;
  for (int i = 0; i < (int)(n); ++i) {
    if (in[i]) continue;
    int minamt = amount[i];
    int next = out[i];
    if (next == -1) continue;
    bool loop = false;
    while (out[next] != -1) {
      minamt = min(minamt, amount[next]);
      arv[next] = true;
      next = out[next];
      if (arv[next]) {
        loop = true;
        break;
      }
    }
    if (!loop) {
      ans.push_back(course(i, next, minamt));
    }
  }
  sort(ans.begin(), ans.end());
  cout << ans.size() << endl;
  for (int i = 0; i < (int)(ans.size()); ++i) {
    printf("%d %d %d\n", ans[i].tank + 1, ans[i].tap + 1, ans[i].amt);
  }
  return 0;
}
