#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:64000000")
const double PI = 3.1415926535897932384626433832795;
const long long ONE = 1LL;
const double EPS = 1e-8;
long long gcd(long long a, long long b) { return (b) ? gcd(b, a % b) : a; }
long long max(long long a, long long b) { return (a > b) ? a : b; }
long long min(long long a, long long b) { return (a < b) ? a : b; }
struct Point {
  unsigned long long x, y;
  Point(unsigned long long _x = 0, unsigned long long _y = 0) : x(_x), y(_y) {}
  void Read() { cin >> x >> y; }
  double Dist(Point a) {
    return sqrt((double)((a.x - x) * (a.x - x) + (a.y - y) * (a.y - y)));
  }
};
struct Res {
  int u, v, c;
  Res() {}
  Res(int _u, int _v, int _c) : u(_u), v(_v), c(_c) {}
  void Out() { cout << u + 1 << " " << v + 1 << " " << c << endl; }
};
const int INF = 10000000;
bool operator<(const Res& a, const Res& b) { return a.u < b.u; }
vector<Res> res;
vector<pair<int, int> > to;
vector<bool> start;
void dfs(int cur, int from, int cap) {
  if (to[cur].first == -1) {
    res.push_back(Res(from, cur, cap));
    return;
  }
  dfs(to[cur].first, from, min(cap, to[cur].second));
}
int main() {
  int n, p;
  cin >> n >> p;
  to.resize(n, make_pair(-1, -1));
  start.resize(n, true);
  int u, v, c;
  for (int i = 0; i < p; ++i) {
    cin >> u >> v >> c;
    --u;
    --v;
    to[u] = make_pair(v, c);
    start[v] = false;
  }
  for (int i = 0; i < n; ++i) {
    if (to[i].first != -1 && start[i]) dfs(i, i, INF);
  }
  sort((res).begin(), (res).end());
  cout << res.size() << endl;
  for (int i = 0; i < res.size(); ++i) {
    res[i].Out();
  }
  return 0;
}
