#include <bits/stdc++.h>
using namespace std;
struct print {
  template <typename T>
  print& operator,(const T& v) {
    (v == '\n') ? (cerr << '\n') : (cerr << v << ", ");
    return *this;
  }
} pr;
long long power(long long b, long long p) {
  long long res = 1, x = b;
  while (p > 0) {
    if (p & 1ll) res = res * x;
    x = x * x;
    p >>= 1;
  }
  return res;
}
long long bigmod(long long b, long long p, long long m) {
  long long res = 1, x = b % m;
  while (p > 0) {
    if (p & 1) res = (res * x) % m;
    x = (x * x) % m;
    p >>= 1;
  }
  return res;
}
int src;
bool vis[1003];
vector<pair<int, int> > adj[1003];
vector<pair<int, pair<int, int> > > ans;
void dfs(int u, int mn) {
  vis[u] = true;
  if (adj[u].size() == 0) {
    ans.push_back(make_pair(src, make_pair(u, mn)));
    return;
  }
  for (pair<int, int> v : adj[u]) {
    if (!vis[v.first]) {
      dfs(v.first, min(mn, v.second));
    }
  }
}
int in_edge[1003], out_edge[1003];
int main() {
  int n, m, u, v, w;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < m; ++i) {
    scanf("%d %d %d", &u, &v, &w);
    --u, --v;
    adj[u].push_back(make_pair(v, w));
    ++in_edge[v];
    ++out_edge[u];
  }
  for (int i = 0; i < n; ++i) {
    if (in_edge[i] == 0 && out_edge[i] > 0) {
      src = i;
      dfs(i, 2e9);
    }
  }
  sort(ans.begin(), ans.end());
  printf("%d\n", ans.size());
  for (auto e : ans) {
    printf("%d %d %d\n", e.first + 1, e.second.first + 1, e.second.second);
  }
}
