#include <bits/stdc++.h>
using namespace std;
vector<int> g[1024];
vector<int> w[1024];
int visited[1000 + 32];
int dest, n;
int see[1024];
int mmin;
void gogo(int v) {
  visited[v] = true;
  if ((int)g[v].size() == 0) {
    dest = v;
    return;
  }
  for (int i = 0; i < g[v].size(); i++) {
    if (!visited[g[v][i]]) {
      mmin = min(mmin, w[v][i]);
      gogo(g[v][i]);
    }
  }
  return;
}
int pos = 0;
int pp[1024 * 1024][3];
int main() {
  memset(visited, false, sizeof(visited));
  memset(see, true, sizeof(see));
  int p;
  cin >> n >> p;
  int from, to, wt;
  for (int i = 0; i < p; i++) {
    cin >> from >> to >> wt;
    from--;
    to--;
    g[from].push_back(to);
    w[from].push_back(wt);
    see[to] = false;
  }
  pos = 0;
  for (int i = 0; i < n; i++) {
    if (((int)g[i].size() == 1) && see[i]) {
      if (!visited[i]) {
        mmin = 1e+9;
        gogo(i);
        pp[pos][0] = i + 1;
        pp[pos][1] = dest + 1;
        pp[pos][2] = mmin;
        pos++;
      }
    }
  }
  printf("%d\n", pos);
  for (int i = 0; i < pos; i++)
    printf("%d %d %d\n", pp[i][0], pp[i][1], pp[i][2]);
  return 0;
}
