#include <bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
using std::pair;
using std::stable_sort;
using std::string;
using std::vector;
using namespace std;
const long long MaxN = 1010;
long long N, M;
long long k;
vector<long long> gin[MaxN];
vector<long long> gout[MaxN];
vector<pair<int, pair<int, int>>> answer(0);
int mas[1010][1010];
int minim = 1000009;
int ret = 0;
void dfs(int n) {
  ret = n;
  if (gout[n].size() != 0) {
    if (mas[n][gout[n][0]] < minim) minim = mas[n][gout[n][0]];
    dfs(gout[n][0]);
  }
}
int main() {
  long long a, b;
  cin >> a >> b;
  for (int i = 0; i < b; i++) {
    int c, d, e;
    cin >> c >> d >> e;
    gout[c].push_back(d);
    gin[d].push_back(c);
    mas[c][d] = e;
  }
  for (int i = 1; i <= a; i++) {
    if (gin[i].size() == 0) {
      if (gout[i].size() != 0) {
        int k = i;
        minim = 1000009;
        dfs(i);
        answer.push_back(make_pair(k, make_pair(ret, minim)));
      }
    }
  }
  if (answer.size() == 0) {
    cout << 0;
  } else {
    cout << answer.size() << endl;
    std::sort(answer.begin(), answer.end());
    for (int i = 0; i < answer.size(); i++) {
      cout << answer[i].first << " " << answer[i].second.first << " "
           << answer[i].second.second << endl;
    }
  }
  return 0;
}
