#include <bits/stdc++.h>
using namespace std;
const int V = 1200;
const int INFI = 1 << 30;
int n, m;
struct node {
  int b, c;
  node() {}
  node(int _b, int _c) {
    b = _b;
    c = _c;
  }
};
struct ANS {
  int a, b, c;
  ANS() {}
  ANS(int _a, int _b, int _c) {
    a = _a;
    b = _b;
    c = _c;
  }
};
vector<node> adj[V];
vector<ANS> ans;
int indeg[V], oudeg[V];
bool vis[V];
int main() {
  int a, b, c;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) adj[i].clear();
  memset(indeg, 0, sizeof(indeg));
  memset(oudeg, 0, sizeof(oudeg));
  for (int i = 0; i < m; i++) {
    scanf("%d%d%d", &a, &b, &c);
    indeg[b]++;
    oudeg[a]++;
    adj[a].push_back(node(b, c));
  }
  memset(vis, 0, sizeof(vis));
  ans.clear();
  for (int i = 1; i <= n; i++)
    if (!vis[i] && indeg[i] == 0 && oudeg[i] > 0) {
      int mind = INFI;
      int j;
      for (j = i; adj[j].size() > 0 && !vis[j]; j = adj[j][0].b) {
        vis[j] = true;
        mind = min(mind, adj[j][0].c);
      }
      if (oudeg[j] == 0) ans.push_back(ANS(i, j, mind));
    }
  printf("%d\n", ans.size());
  for (int i = 0; i < ans.size(); i++)
    printf("%d %d %d\n", ans[i].a, ans[i].b, ans[i].c);
}
