#include <bits/stdc++.h>
using namespace std;
int n, m;
int din[1003], dout[1003];
int nin[1003], nout[1003];
vector<pair<pair<int, int>, int> > ans;
int main() {
  scanf("%d%d", &n, &m);
  memset(nin, -1, sizeof(nin));
  memset(nout, -1, sizeof(nout));
  for (int i = 0; i < m; i++) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    a--, b--;
    dout[a] += c;
    nout[a] = b;
    din[b] += c;
    nin[b] = a;
  }
  for (int i = 0; i < n; i++) {
    if (nin[i] == -1 && nout[i] != -1) {
      int p = i;
      int cap = dout[p];
      int dest = p;
      while (p != -1) {
        dest = p;
        if (nout[p] != -1) {
          cap = min(cap, dout[p]);
        }
        p = nout[p];
      }
      ans.push_back(make_pair(make_pair(i + 1, dest + 1), cap));
    }
  }
  printf("%d\n", ans.size());
  for (int i = 0; i < ans.size(); i++) {
    printf("%d %d %d\n", ans[i].first.first, ans[i].first.second,
           ans[i].second);
  }
  return 0;
}
