#include <bits/stdc++.h>
using namespace std;
int house[1002][1002];
bool istank[1002], istap[1002];
vector<pair<pair<int, int>, int> > ret;
void augment(int x) {
  int cb[1002];
  for (int i = 0; i < 1002; ++i) cb[i] = 100000000;
  queue<int> Q;
  Q.push(x);
  while (!Q.empty()) {
    int now = Q.front();
    Q.pop();
    if (istap[now]) {
      ret.push_back(make_pair(make_pair(x, now), cb[now]));
    }
    for (int i = 1; i <= 1000; ++i) {
      if (house[now][i] > 0 && cb[i] == 100000000) {
        cb[i] = min(cb[now], house[now][i]);
        Q.push(i);
      }
    }
  }
}
int main() {
  for (int i = 0; i < 1002; ++i) {
    for (int j = 0; j < 1002; ++j) {
      house[i][j] = 0;
    }
    istank[i] = 0;
    istap[i] = 0;
  }
  int h, p;
  scanf("%d %d", &h, &p);
  for (int i = 0; i < p; ++i) {
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    house[a][b] = c;
  }
  for (int i = 1; i <= h; ++i) {
    bool btan = 0, btap = 0;
    for (int j = 1; j <= h; ++j) {
      if (house[i][j] > 0) btan = 1;
      if (house[j][i] > 0) btap = 1;
    }
    if (btan && !btap) istank[i] = 1;
    if (!btan && btap) istap[i] = 1;
  }
  for (int i = 1; i <= h; ++i) {
    if (istank[i]) {
      augment(i);
    }
  }
  sort(ret.begin(), ret.end());
  printf("%d\n", ret.size());
  for (int i = 0; i < ret.size(); ++i) {
    printf("%d %d %d\n", ret[i].first.first, ret[i].first.second,
           ret[i].second);
  }
  return 0;
}
