#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 9;
vector<pair<int, int> > in[1010];
vector<pair<int, int> > out[1010];
vector<int> vis(1010, 0);
pair<int, int> fdfs(int v) {
  vis[v] = 1;
  if (!(int)(out[v].size())) return make_pair(v, INF);
  if (vis[out[v][0].first]) return make_pair(-1, INF);
  pair<int, int> aux = fdfs(out[v][0].first);
  aux.second = min(aux.second, out[v][0].second);
  return aux;
}
int main() {
  int N, M, v, w, c;
  cin >> N >> M;
  for (int i = 0; i < (int)(M); i++) {
    cin >> v >> w >> c;
    v--;
    w--;
    out[v].push_back(make_pair(w, c));
    in[w].push_back(make_pair(v, c));
  }
  vector<pair<int, pair<int, int> > > ans;
  for (int i = 0; i < (int)(N); i++) {
    if (!(int)(in[i].size())) {
      pair<int, int> aux = fdfs(i);
      if (aux.first != -1 and i != aux.first) ans.push_back(make_pair(i, aux));
    }
  }
  sort((ans).begin(), (ans).end());
  cout << (int)(ans.size()) << endl;
  for (int i = 0; i < (int)((int)(ans.size())); i++)
    cout << ans[i].first + 1 << " " << ans[i].second.first + 1 << " "
         << ans[i].second.second << endl;
}
