#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > adj[1001];
int vis[1001];
int in[1001];
int out[1001];
int minwt = INT_MAX;
vector<int> weight;
vector<pair<int, int> > vc;
void dfs(int s, int prev) {
  if (vis[s]) return;
  vis[s] = 1;
  if (in[s] == 1 && out[s] == 0) {
    vc.push_back(make_pair(prev, s));
    weight.push_back(minwt);
    return;
  }
  for (int i = 0; i < adj[s].size(); i++) {
    pair<int, int> p = adj[s][i];
    int wt = p.first;
    int u = p.second;
    if (!vis[u]) {
      minwt = min(minwt, wt);
      dfs(u, prev);
    }
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  memset(in, 0, sizeof(in));
  memset(out, 0, sizeof(out));
  for (int i = 0; i < m; i++) {
    int u, v, w;
    cin >> u >> v >> w;
    adj[u].push_back(make_pair(w, v));
    out[u]++;
    in[v]++;
  }
  memset(vis, 0, sizeof(vis));
  for (int i = 1; i <= n; i++) {
    if (!vis[i] && out[i] == 1 && in[i] == 0) {
      minwt = INT_MAX;
      dfs(i, i);
    }
  }
  cout << vc.size() << endl;
  for (int i = 0; i < vc.size(); i++) {
    cout << vc[i].first << " " << vc[i].second << " " << weight[i] << endl;
  }
}
