#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int cnt = 0;
struct node {
  int a, b, c;
  void fun(int x, int y, int z) {
    a = x;
    b = y;
    c = z;
  }
} res[N];
vector<pair<int, int> > adj[N];
int degree_in[N], degree_out[N];
void dfs(int fa, int cur, int imin) {
  if ((int)adj[cur].size() == 0) {
    res[cnt++].fun(fa, cur, imin);
  } else {
    for (int i = 0; i < (int)adj[cur].size(); i++) {
      int a = adj[cur][i].first, b = adj[cur][i].second;
      dfs(fa, a, min(b, imin));
    }
  }
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    adj[a].push_back(make_pair(b, c));
    degree_in[a]++;
    degree_out[b]++;
  }
  for (int i = 1; i <= n; i++) {
    if (degree_in[i] == 1 && degree_out[i] == 0) dfs(i, i, 1 << 30);
  }
  printf("%d\n", cnt);
  for (int i = 0; i < cnt; i++)
    printf("%d %d %d\n", res[i].a, res[i].b, res[i].c);
  return 0;
}
