#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1000000000")
using namespace std;
int n, p;
vector<int> g[1001];
int color[1001];
int in[1001];
int a, b, mx, d;
map<pair<int, int>, int> dis;
int dfs(int v, int &en) {
  color[v] = 1;
  if (g[v].size() == 0) {
    en = v;
    return 0x3F3F3F3F;
  }
  for (int(i) = (0); (i) < int(g[v].size()); ++(i)) {
    int to = g[v][i];
    if (color[to] == 1) {
      return -1;
    } else {
      int res = dfs(to, en);
      if (res != -1)
        return min(dis[pair<int, int>(v, to)], res);
      else
        return -1;
    }
  }
  color[v] = 2;
}
int main() {
  scanf("%d %d", &n, &p);
  for (int(i) = (0); (i) < int(p); ++(i)) {
    scanf("%d %d %d", &a, &b, &d);
    --a, --b;
    g[a].push_back(b);
    in[b] = 1;
    dis[pair<int, int>(a, b)] = d;
  }
  vector<pair<pair<int, int>, int> > v;
  for (int(i) = (0); (i) < int(n); ++(i)) {
    if (!in[i] && g[i].size() != 0) {
      int en;
      int d = dfs(i, en);
      if (d != -1) {
        v.push_back(pair<pair<int, int>, int>(pair<int, int>(i, en), d));
      }
    }
  }
  cout << v.size() << endl;
  for (auto x : v) {
    cout << x.first.first + 1 << " " << x.first.second + 1 << " " << x.second
         << endl;
  }
  cin.sync();
  cin.get();
  return 0;
}
