#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 1024;
const int E = 31086;
struct edge {
  int x, y, nxt;
  int c;
} bf[E];
int ne, head[N], cur[N], ps[N], dep[N];
void addedge(int x, int y, int c) {
  bf[ne].x = x;
  bf[ne].y = y;
  bf[ne].c = c;
  bf[ne].nxt = head[x];
  head[x] = ne++;
  bf[ne].x = y;
  bf[ne].y = x;
  bf[ne].c = 0;
  bf[ne].nxt = head[y];
  head[y] = ne++;
}
int flow(int n, int s, int t) {
  int tr, res = 0;
  int i, j, k, f, r, top;
  while (1) {
    memset(dep, -1, n * sizeof(int));
    for (f = dep[ps[0] = s] = 0, r = 1; f != r;)
      for (i = ps[f++], j = head[i]; j != -1; j = bf[j].nxt) {
        if (bf[j].c && -1 == dep[k = bf[j].y]) {
          dep[k] = dep[i] + 1;
          ps[r++] = k;
          if (k == t) {
            f = r;
            break;
          }
        }
      }
    if (-1 == dep[t]) break;
    memcpy(cur, head, n * sizeof(int));
    for (i = s, top = 0;;) {
      if (i == t) {
        for (k = 0, tr = inf; k < top; ++k)
          if (bf[ps[k]].c < tr) tr = bf[ps[f = k]].c;
        for (k = 0; k < top; ++k) bf[ps[k]].c -= tr, bf[ps[k] ^ 1].c += tr;
        res += tr;
        i = bf[ps[top = f]].x;
      }
      for (j = cur[i]; cur[i] != -1; j = cur[i] = bf[cur[i]].nxt)
        if (bf[j].c && dep[i] + 1 == dep[bf[j].y]) break;
      if (cur[i] != -1) {
        ps[top++] = cur[i];
        i = bf[cur[i]].y;
      } else {
        if (0 == top) break;
        dep[i] = -1;
        i = bf[ps[--top]].x;
      }
    }
  }
  return res;
}
struct tanktap {
  int tank;
  int tap;
  int diameter;
  tanktap();
  tanktap(int _tank, int _tap, int dia) {
    tank = _tank;
    tap = _tap;
    diameter = dia;
  }
};
bool cmp(tanktap a1, tanktap a2) { return a1.tank < a2.tank; }
vector<vector<pair<int, int> > > g;
bool out[N], in[N];
int a[N], b[N], d[N];
int minl;
int dfs(int u) {
  if (g[u].size() == 0) return u;
  minl = min(minl, g[u][0].second);
  return dfs(g[u][0].first);
}
int main() {
  int n, p;
  scanf("%d %d", &n, &p);
  g.resize(n + 1);
  for (int i = 0; i < p; ++i) {
    scanf("%d %d %d", &a[i], &b[i], &d[i]);
    g[a[i]].push_back(make_pair(b[i], d[i]));
    out[a[i]] = true;
    in[b[i]] = true;
  }
  vector<tanktap> vec;
  for (int i = 1; i <= n; ++i) {
    if (out[i] && !in[i]) {
      minl = inf;
      int v = dfs(i);
      vec.push_back(tanktap(i, v, minl));
    }
  }
  printf("%d\n", (int)vec.size());
  for (int i = 0; i < vec.size(); ++i) {
    printf("%d %d %d\n", vec[i].tank, vec[i].tap, vec[i].diameter);
  }
  return 0;
}
