#include <bits/stdc++.h>
using namespace std;
typedef struct {
  int v, d;
} Edge_t;
const int maxn = 1005;
int ideg[maxn], odeg[maxn];
vector<Edge_t> E[maxn];
typedef struct tuple_t {
  int s, e, d;
  friend bool operator<(const tuple_t& a, const tuple_t& b) {
    return a.s < b.s;
  }
} tuple_t;
vector<tuple_t> ans;
tuple_t t;
void dfs(int u, int d) {
  if (odeg[u] == 0 && u != t.s) {
    t.d = d;
    t.e = u;
    ans.push_back(t);
    return;
  }
  int v, d_;
  for (int i = 0; i < ((int)(E[u]).size()); ++i) {
    v = E[u][i].v;
    d_ = E[u][i].d;
    d_ = min(d_, d);
    dfs(v, d_);
  }
}
int main() {
  ios::sync_with_stdio(false);
  int n, m;
  int u, v, d;
  Edge_t e;
  memset(ideg, 0, sizeof(ideg));
  memset(odeg, 0, sizeof(odeg));
  scanf("%d %d", &n, &m);
  while (m--) {
    scanf("%d %d %d", &u, &e.v, &e.d);
    E[u].push_back(e);
    ++ideg[e.v];
    ++odeg[u];
  }
  for (int i = 1; i < n + 1; ++i) {
    if (ideg[i] == 0) {
      t.s = i;
      dfs(i, INT_MAX);
    }
  }
  sort((ans).begin(), (ans).end());
  n = ((int)(ans).size());
  printf("%d\n", n);
  for (int i = 0; i < n; ++i)
    printf("%d %d %d\n", ans[i].s, ans[i].e, ans[i].d);
  return 0;
}
