#include <bits/stdc++.h>
using namespace std;
const int N = 100000;
vector<vector<pair<int, int> > > g(N);
vector<int> vis(N, 0);
vector<long long> bal(N, 0);
void dfs(int u) {
  vis[u] = 1;
  for (auto [v, w] : g[u]) {
    bal[v] += w;
    bal[u] -= w;
    if (vis[v] == 0) {
      dfs(v);
    }
  }
}
int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < m; i++) {
    int u, v, w;
    scanf("%d %d %d", &u, &v, &w);
    g[--u].push_back({--v, w});
  }
  for (int i = 0; i < n; i++) {
    if (vis[i] == 0) {
      dfs(i);
    }
  }
  set<pair<long long, int> > pos, neg;
  for (int i = 0; i < n; i++) {
    if (bal[i] < 0) {
      neg.insert({-bal[i], i});
    }
    if (bal[i] > 0) {
      pos.insert({bal[i], i});
    }
  }
  vector<pair<pair<int, int>, long long> > ans;
  while (!pos.empty() && !neg.empty()) {
    auto [amnt1, give] = *neg.rbegin();
    auto [amnt2, take] = *pos.begin();
    pos.erase(pos.begin());
    neg.erase(prev(neg.end()));
    long long mn = min(amnt1, amnt2);
    ans.push_back({{give, take}, mn});
    amnt1 -= mn;
    amnt2 -= mn;
    if (amnt1 > 0) {
      neg.insert({amnt1, give});
    }
    if (amnt2 > 0) {
      pos.insert({amnt2, take});
    }
  }
  printf("%d\n", int(ans.size()));
  for (auto [x, y] : ans) {
    printf("%d %d %lld\n", x.first + 1, x.second + 1, y);
  }
}
