There are $n$ people in this world, conveniently numbered $1$ through $n$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $d(a,b)$ denote the debt of $a$ towards $b$, or $0$ if there is no such debt.

Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money. 

When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done:  Let $d(a,b) > 0$ and $d(c,d) > 0$ such that $a \neq c$ or $b \neq d$. We can decrease the $d(a,b)$ and $d(c,d)$ by $z$ and increase $d(c,b)$ and $d(a,d)$ by $z$, where $0 < z \leq \min(d(a,b),d(c,d))$.  Let $d(a,a) > 0$. We can set $d(a,a)$ to $0$. 

The total debt is defined as the sum of all debts:

$$\Sigma_d = \sum_{a,b} d(a,b)$$

Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.


-----Input-----

The first line contains two space separated integers $n$ ($1 \leq n \leq 10^5$) and $m$ ($0 \leq m \leq 3\cdot 10^5$), representing the number of people and the number of debts, respectively.

$m$ lines follow, each of which contains three space separated integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), $d_i$ ($1 \leq d_i \leq 10^9$), meaning that the person $u_i$ borrowed $d_i$ burles from person $v_i$.


-----Output-----

On the first line print an integer $m'$ ($0 \leq m' \leq 3\cdot 10^5$), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint.

After that print $m'$ lines, $i$-th of which contains three space separated integers $u_i, v_i, d_i$, meaning that the person $u_i$ owes the person $v_i$ exactly $d_i$ burles. The output must satisfy $1 \leq u_i, v_i \leq n$, $u_i \neq v_i$ and $0 < d_i \leq 10^{18}$.

For each pair $i \neq j$, it should hold that $u_i \neq u_j$ or $v_i \neq v_j$. In other words, each pair of people can be included at most once in the output.


-----Examples-----
Input
3 2
1 2 10
2 3 5

Output
2
1 2 5
1 3 5

Input
3 3
1 2 10
2 3 15
3 1 10

Output
1
2 3 5

Input
4 2
1 2 12
3 4 8

Output
2
1 2 12
3 4 8

Input
3 4
2 3 1
2 3 2
2 3 4
2 3 8

Output
1
2 3 15



-----Note-----

In the first example the optimal sequence of operations can be the following:  Perform an operation of the first type with $a = 1$, $b = 2$, $c = 2$, $d = 3$ and $z = 5$. The resulting debts are: $d(1, 2) = 5$, $d(2, 2) = 5$, $d(1, 3) = 5$, all other debts are $0$;  Perform an operation of the second type with $a = 2$. The resulting debts are: $d(1, 2) = 5$, $d(1, 3) = 5$, all other debts are $0$. 

In the second example the optimal sequence of operations can be the following:  Perform an operation of the first type with $a = 1$, $b = 2$, $c = 3$, $d = 1$ and $z = 10$. The resulting debts are: $d(3, 2) = 10$, $d(2, 3) = 15$, $d(1, 1) = 10$, all other debts are $0$;  Perform an operation of the first type with $a = 2$, $b = 3$, $c = 3$, $d = 2$ and $z = 10$. The resulting debts are: $d(2, 2) = 10$, $d(3, 3) = 10$, $d(2, 3) = 5$, $d(1, 1) = 10$, all other debts are $0$;  Perform an operation of the second type with $a = 2$. The resulting debts are: $d(3, 3) = 10$, $d(2, 3) = 5$, $d(1, 1) = 10$, all other debts are $0$;  Perform an operation of the second type with $a = 3$. The resulting debts are: $d(2, 3) = 5$, $d(1, 1) = 10$, all other debts are $0$;  Perform an operation of the second type with $a = 1$. The resulting debts are: $d(2, 3) = 5$, all other debts are $0$.

Difficulty: HARD
Tags: Graph algorithms

Constructive algorithms

Amortized analysis

Implementation

Greedy algorithms

Mathematics

Data structures
Skill types: Data structures

Amortized analysis

Greedy algorithms

Starter code:

Solutions:
(n, m) = map(int, input().split())
d = {}
for i in range(m):
	(x, y, a) = map(int, input().split())
	d[x] = d.get(x, 0) - a
	d[y] = d.get(y, 0) + a
pos = []
neg = []
for i in d:
	if d[i] < 0:
		neg.append([d[i], i])
	elif d[i] > 0:
		pos.append([d[i], i])
ans = []
i = 0
j = 0
while i < len(neg) and j < len(pos):
	z = min(-neg[i][0], pos[j][0])
	ans.append([neg[i][1], pos[j][1], z])
	neg[i][0] += z
	pos[j][0] -= z
	if pos[j][0] == 0:
		j += 1
	if neg[i][0] == 0:
		i += 1
print(len(ans))
for i in ans:
	print(*i)


import sys
import math
input = sys.stdin.readline
(n, m) = map(int, input().split())
arr = [0] * n
for i in range(m):
	(u, v, d) = map(int, input().split())
	arr[u - 1] -= d
	arr[v - 1] += d
pos = []
neg = []
for i in range(n):
	if arr[i] > 0:
		pos.append([i, arr[i]])
	elif arr[i] < 0:
		neg.append([i, -arr[i]])
ans = []
j = 0
for i in range(len(neg)):
	while neg[i][1] > 0:
		if pos[j][1] >= neg[i][1]:
			ans.append([neg[i][0] + 1, pos[j][0] + 1, neg[i][1]])
			pos[j][1] -= neg[i][1]
			neg[i][1] = 0
			if pos[j][1] == 0:
				j += 1
		else:
			ans.append([neg[i][0] + 1, pos[j][0] + 1, pos[j][1]])
			neg[i][1] -= pos[j][1]
			pos[j][1] = 0
			j += 1
print(len(ans))
for i in range(len(ans)):
	print(*ans[i])


from collections import deque
import sys
input = sys.stdin.buffer.readline
(n, m) = map(int, input().split())
balance = [0 for i in range(n)]
for _ in range(m):
	(u, v, d) = map(int, input().split())
	balance[u - 1] -= d
	balance[v - 1] += d
bgive = [[x, -balance[x]] for x in range(n) if balance[x] < 0]
btake = [[x, balance[x]] for x in range(n) if balance[x] > 0]
tdbt = 0
for x in balance:
	if x > 0:
		tdbt += x
	else:
		tdbt -= x
i = 0
j = 0
total = 0
printall = []
printall.append
while tdbt > 0:
	if bgive[i][1] > btake[j][1]:
		printall.append([bgive[i][0] + 1, btake[j][0] + 1, btake[j][1]])
		bgive[i][1] -= btake[j][1]
		tdbt -= 2 * btake[j][1]
		j += 1
	elif bgive[i][1] < btake[j][1]:
		printall.append([bgive[i][0] + 1, btake[j][0] + 1, bgive[i][1]])
		btake[j][1] -= bgive[i][1]
		tdbt -= 2 * bgive[i][1]
		i += 1
	else:
		printall.append([bgive[i][0] + 1, btake[j][0] + 1, btake[j][1]])
		tdbt -= 2 * btake[j][1]
		j += 1
		i += 1
	total += 1
print(total)
for x in printall:
	print(' '.join(map(str, x)))


import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, k) = map(int, input().split())
debts = [0] * (n + 1)
for _ in range(k):
	(a, b, amt) = map(int, input().split())
	debts[a] += amt
	debts[b] -= amt
ameer_log = {}
gareeb_log = {}
for i in range(1, n + 1):
	if debts[i] < 0:
		ameer_log[i] = -1 * debts[i]
	elif debts[i] > 0:
		gareeb_log[i] = debts[i]
rich = sorted(ameer_log, key=ameer_log.get, reverse=True)
poor = sorted(gareeb_log, key=gareeb_log.get, reverse=True)
(i, j) = (0, 0)
ans = []
while i < len(rich) and j < len(poor):
	(rn, rd, pn, pd) = (rich[i], ameer_log[rich[i]], poor[j], gareeb_log[poor[j]])
	pay = min(rd, pd)
	if rd == pd:
		ans.append([pn, rn, rd])
		i += 1
		j += 1
	elif pay == pd:
		ans.append([pn, rn, pay])
		ameer_log[rich[i]] -= pd
		j += 1
	else:
		ans.append([pn, rn, pay])
		gareeb_log[poor[j]] -= rd
		i += 1
print(len(ans))
for x in ans:
	print(x[0], x[1], x[2])


(n, m) = map(int, input().split())
bal = [0] * n
for i in range(m):
	(x, y, z) = map(int, input().split())
	bal[x - 1] -= z
	bal[y - 1] += z
owe = []
for i in range(n):
	if bal[i] < 0:
		owe.append([i, -bal[i]])
ans = []
for i in range(n):
	while bal[i] > 0 and owe:
		val = min(bal[i], owe[0][1])
		ans.append([owe[0][0] + 1, i + 1, val])
		bal[i] -= val
		owe[0][1] -= val
		if owe[0][1] == 0:
			owe.pop(0)
print(len(ans))
for i in range(len(ans)):
	print(' '.join(map(str, ans[i])))


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
val = [0] * n
for i in range(m):
	(a, b, cost) = info[i]
	a -= 1
	b -= 1
	val[a] -= cost
	val[b] += cost
minus = []
plus = []
for i in range(n):
	if val[i] < 0:
		minus.append([i, -val[i]])
	if val[i] > 0:
		plus.append([i, val[i]])
ans = []
num1 = 0
for (num2, cost) in minus:
	a = num2 + 1
	value = cost
	while True:
		if value == 0:
			break
		if num1 >= len(plus):
			break
		if plus[num1][1] <= value:
			ans.append((a, plus[num1][0] + 1, plus[num1][1]))
			value -= plus[num1][1]
			num1 += 1
		else:
			ans.append((a, plus[num1][0] + 1, value))
			plus[num1][1] -= value
			break
print(len(ans))
for i in ans:
	print(*i)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 30, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
(n, m) = map(int, input().split())
d = defaultdict(int)
e = []
p = [i for i in range(n + 1)]
size = [1 for i in range(n + 1)]
pos = [[] for i in range(n + 1)]
neg = [[] for i in range(n + 1)]

def get(a):
	if p[a] != a:
		p[a] = get(p[a])
	return p[a]

def union(a, b):
	a = get(a)
	b = get(b)
	if size[a] > size[b]:
		(a, b) = (b, a)
	size[b] += size[a]
	p[a] = b
	for i in neg[a]:
		neg[b].append(i)
	for i in pos[a]:
		pos[b].append(i)

def find(a):
	t = 0
	for i in range(len(neg[a])):
		while d[neg[a][i]] < 0:
			t1 = min(abs(d[neg[a][i]]), d[pos[a][t]])
			d[neg[a][i]] += t1
			d[pos[a][t]] -= t1
			if t1 != 0:
				e.append((neg[a][i], pos[a][t], t1))
			if d[pos[a][t]] == 0:
				t += 1
l = []
ans = 0
for i in range(m):
	(a, b, c) = map(int, input().split())
	d[a] -= c
	d[b] += c
	l.append((a, b))
for i in d:
	ans += abs(d[i])
	if d[i] >= 0:
		pos[i].append(i)
	else:
		neg[i].append(i)
ans //= 2
for i in range(m):
	(a, b) = l[i]
	if get(a) != get(b):
		union(get(a), get(b))
for i in range(1, n + 1):
	if get(i) == i:
		find(i)
print(len(e))
for i in e:
	print(*i)


from collections import defaultdict
(n, m) = map(int, input().split())
d = {i + 1: 0 for i in range(n)}
for i in range(m):
	(u, v, d1) = map(int, input().split())
	d[u] = d[u] + d1
	d[v] = d[v] - d1
i = 1
j = 1
ans = []
while i < n + 1:
	if d[i] < 0:
		while d[j] <= 0:
			j = j + 1
		delta = min(-d[i], d[j])
		d[i] = d[i] + delta
		d[j] = d[j] - delta
		ans.append((j, i, delta))
	else:
		i = i + 1
print(len(ans))
for i in ans:
	print(*i)


(n, m) = map(int, input().split())
balance = [0] * n
for _ in range(m):
	(u, v, w) = map(int, input().split())
	u -= 1
	v -= 1
	balance[u] -= w
	balance[v] += w
i = 0
j = 0
ans = []
while i < n:
	if balance[i] < 0:
		while balance[j] <= 0:
			j += 1
		delta = min(-balance[i], balance[j])
		balance[i] += delta
		balance[j] -= delta
		ans.append((i + 1, j + 1, delta))
	else:
		i += 1
print(len(ans))
for edge in ans:
	print(*edge)


from __future__ import division, print_function

def main():
	import sys
	data = iter(map(int, sys.stdin.buffer.read().decode('ascii').split()))
	(n, m) = (next(data), next(data))
	val = [0] * (n + 1)
	for _ in range(m):
		(u, v, d) = (next(data) for i in range(3))
		val[u] -= d
		val[v] += d
	neg = [(u, -val[u]) for u in range(1, n + 1) if val[u] < 0]
	pos = [(u, val[u]) for u in range(1, n + 1) if val[u] > 0]
	tot = sum((d for (_, d) in pos))
	val = None
	res = []
	while tot:
		left = neg[-1][1]
		right = pos[-1][1]
		if left == 0:
			neg.pop()
			continue
		if right == 0:
			pos.pop()
			continue
		if left > right:
			res.append((neg[-1][0], pos[-1][0], right))
			pos.pop()
			neg[-1] = (neg[-1][0], left - right)
			tot -= right
		else:
			res.append((neg[-1][0], pos[-1][0], left))
			neg.pop()
			pos[-1] = (pos[-1][0], right - left)
			tot -= left
	print(len(res))
	print('\n'.join(('%d %d %d' % (u, v, d) for (u, v, d) in res)))
	return 0
main()


from sys import stdin, stdout, setrecursionlimit
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log, log2
from random import seed, randint
from datetime import datetime
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from collections import defaultdict as dd
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def def_value():
	return 0

def def_inf():
	return inf

def atoi(s):
	return ord(s) - ord('0')

def inc(s, n=1):
	return chr((ord(s) - ord('a') + n) % 26 + ord('a'))

class XY:

	def __init__(self, x, y):
		self.x = x
		self.y = y

def rotate(a, b, c):
	ang = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y)
	if ang == 0:
		return 0
	else:
		return ang / abs(ang)

def phi(n):
	(res, p) = (n, 2)
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			res -= res // p
		p += 1
	if n > 1:
		res -= res // n
	return res
(n, m) = mp()
adj = [[] for i in range(n)]
for i in range(m):
	(u, v, d) = mp()
	adj[u - 1].append(-d)
	adj[v - 1].append(d)
tot = l1d(n)
(pos, neg) = ([], [])
for i in range(n):
	tot[i] = sum(adj[i])
	if tot[i] > 0:
		pos.append([tot[i], i + 1])
	elif tot[i] < 0:
		neg.append([-tot[i], i + 1])
pos = sorted(pos, key=lambda x: -x[0])
neg = sorted(neg, key=lambda x: -x[0])
edges = []
(i, j) = (0, 0)
while i < len(pos) and j < len(neg):
	if pos[i][0] == neg[j][0]:
		edges.append([neg[j][1], pos[i][1], pos[i][0]])
		(i, j) = (i + 1, j + 1)
	elif pos[i][0] < neg[j][0]:
		edges.append([neg[j][1], pos[i][1], pos[i][0]])
		neg[j][0] -= pos[i][0]
		i += 1
	else:
		edges.append([neg[j][1], pos[i][1], neg[j][0]])
		pos[i][0] -= neg[j][0]
		j += 1
print(len(edges))
for i in range(len(edges)):
	print(*edges[i])


import sys
input = sys.stdin.buffer.readline
from collections import defaultdict

def getlist():
	return list(map(int, input().split()))

def main():
	(N, M) = getlist()
	D = defaultdict(int)
	for i in range(M):
		(u, v, d) = getlist()
		D[u] -= d
		D[v] += d
	start = []
	startD = []
	end = []
	endD = []
	for i in D:
		if D[i] > 0:
			end.append(i)
			endD.append(D[i])
		if D[i] < 0:
			start.append(i)
			startD.append(D[i])
	X = len(start)
	i = 0
	j = 0
	m = 0
	ans = []
	if X == 0:
		print(0)
		return
	while True:
		S = startD[i]
		T = endD[j]
		if S + T > 0:
			ans.append([start[i], end[j], -S])
			endD[j] += S
			i += 1
		elif S + T < 0:
			ans.append([start[i], end[j], T])
			startD[i] += T
			j += 1
		else:
			ans.append([start[i], end[j], T])
			i += 1
			j += 1
		m += 1
		if i >= X:
			break
	print(m)
	for i in range(m):
		print(' '.join(list(map(str, ans[i]))))
main()


import sys
input = sys.stdin.readline
from collections import defaultdict as dd
(n, m) = map(int, input().split())
d = dd(int)
for i in range(m):
	(u, v, val) = map(int, input().split())
	d[u] += val
	d[v] -= val
p = []
n = []
for i in d:
	if d[i] < 0:
		n.append((d[i], i))
	elif d[i] > 0:
		p.append((d[i], i))
n.sort()
p.sort(reverse=True)
i = 0
j = 0
res = []
while i < len(n) and j < len(p):
	(a, b) = (n[i][1], p[j][1])
	(aa, bb) = (d[a], d[b])
	aa = -aa
	if aa < bb:
		res.append((b, a, aa))
		d[b] -= aa
		i += 1
	elif aa > bb:
		res.append((b, a, bb))
		d[a] += bb
		j += 1
	else:
		res.append((b, a, aa))
		i += 1
		j += 1
print(len(res))
for i in res:
	print(*i)


def f():
	(n, m) = [int(s) for s in input().split()]
	bank = [0] * (n + 1)
	for i in range(m):
		(u, v, d) = [int(s) for s in input().split()]
		bank[u] += d
		bank[v] -= d
	borrow = []
	lend = []
	for i in range(1, n + 1):
		if bank[i] > 0:
			borrow.append([i, bank[i]])
		if bank[i] < 0:
			lend.append([i, -bank[i]])
	memo = []
	ind = 0
	for (lender, money) in lend:
		while borrow[ind][1] < money:
			memo.append((borrow[ind][0], lender, borrow[ind][1]))
			money -= borrow[ind][1]
			ind += 1
		if borrow[ind][1] == money:
			memo.append((borrow[ind][0], lender, money))
			ind += 1
		else:
			memo.append((borrow[ind][0], lender, money))
			borrow[ind][1] -= money
	print(len(memo))
	for (u, v, d) in memo:
		print('{} {} {}'.format(u, v, d))
f()


import sys
(N, M) = map(int, input().split())
money = [0] * N
for (u, v, d) in (map(int, l.split()) for l in sys.stdin):
	money[u - 1] -= d
	money[v - 1] += d
(plus, minus) = ([], [])
for (i, m) in enumerate(money):
	if m > 0:
		plus.append([i, m])
	elif m < 0:
		minus.append([i, -m])
ans = []
for (i, m) in minus:
	while m > 0:
		x = m if m < plus[-1][1] else plus[-1][1]
		ans.append((i + 1, plus[-1][0] + 1, x))
		m -= x
		if plus[-1][1] == x:
			plus.pop()
		else:
			plus[-1][1] -= x
print(len(ans))
for l in ans:
	print(*l)


import sys
input = sys.stdin.readline
l = input().split()
n = int(l[0])
m = int(l[1])
owe = [0 for i in range(n)]
for i in range(m):
	l = input().split()
	u = int(l[0])
	v = int(l[1])
	d = int(l[2])
	u -= 1
	v -= 1
	owe[u] += d
	owe[v] -= d
owers = []
loan = []
for i in range(n):
	if owe[i] > 0:
		owers.append([i, owe[i]])
	elif owe[i] < 0:
		loan.append([i, -owe[i]])
z = len(owers)
y = len(loan)
currz = 0
curry = 0
l = []
while currz != z:
	if owers[currz][1] <= loan[curry][1]:
		l.append((owers[currz][0], loan[curry][0], owers[currz][1]))
		loan[curry][1] -= owers[currz][1]
		if loan[curry][1] == 0:
			curry += 1
		currz += 1
	else:
		l.append((owers[currz][0], loan[curry][0], loan[curry][1]))
		owers[currz][1] -= loan[curry][1]
		if owers[currz][1] == 0:
			currz += 1
		curry += 1
print(len(l))
for i in l:
	print(i[0] + 1, i[1] + 1, i[2])


import sys

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
(n, k) = get_ints()
dic = dict()
for _ in range(k):
	(u, v, d) = get_ints()
	if u not in dic:
		dic[u] = -d
	else:
		dic[u] -= d
	if v not in dic:
		dic[v] = d
	else:
		dic[v] += d
dic_neg = dict()
dic_pos = dict()
for (key, value) in dic.items():
	if value > 0:
		dic_pos[key] = value
	elif value < 0:
		dic_neg[key] = value
li_pos = sorted(dic_pos.items(), key=lambda kv: [kv[1], kv[0]], reverse=True)
li_neg = sorted(dic_neg.items(), key=lambda kv: [kv[1], kv[0]])
li_pos = [[key, val] for (key, val) in li_pos]
li_neg = [[key, val] for (key, val) in li_neg]
(pos_ind, neg_ind) = (0, 0)
li = []
while pos_ind != len(li_pos):
	if li_pos[pos_ind][1] >= abs(li_neg[neg_ind][1]):
		li.append([li_neg[neg_ind][0], li_pos[pos_ind][0], abs(li_neg[neg_ind][1])])
		li_pos[pos_ind][1] += li_neg[neg_ind][1]
		li_neg[neg_ind][1] = 0
	else:
		li.append([li_neg[neg_ind][0], li_pos[pos_ind][0], li_pos[pos_ind][1]])
		li_neg[neg_ind][1] += li_pos[pos_ind][1]
		li_pos[pos_ind][1] = 0
	if li_neg[neg_ind][1] == 0:
		neg_ind += 1
	if li_pos[pos_ind][1] == 0:
		pos_ind += 1
print(len(li))
for i in li:
	print(*i)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
D = [0] * (n + 1)
for i in range(m):
	(x, y, z) = map(int, input().split())
	D[x] += z
	D[y] -= z
PLUS = []
MINUS = []
for i in range(n + 1):
	if D[i] > 0:
		PLUS.append([D[i], i])
	elif D[i] < 0:
		MINUS.append([-D[i], i])
Pind = 0
Mind = 0
PMAX = len(PLUS)
MMAX = len(MINUS)
ANS = []
while Pind < PMAX and Mind < MMAX:
	if PLUS[Pind][0] > MINUS[Mind][0]:
		PLUS[Pind][0] -= MINUS[Mind][0]
		ANS.append((PLUS[Pind][1], MINUS[Mind][1], MINUS[Mind][0]))
		Mind += 1
	elif PLUS[Pind][0] == MINUS[Mind][0]:
		ANS.append((PLUS[Pind][1], MINUS[Mind][1], MINUS[Mind][0]))
		Mind += 1
		Pind += 1
	else:
		MINUS[Mind][0] -= PLUS[Pind][0]
		ANS.append((PLUS[Pind][1], MINUS[Mind][1], PLUS[Pind][0]))
		Pind += 1
print(len(ANS))
for (x, y, z) in ANS:
	print(x, y, z)


from sys import stdin

def iin():
	return int(stdin.readline())

def lin():
	return list(map(int, stdin.readline().split()))

def main():
	(n, m) = lin()
	dept = [0] * (n + 1)
	for _ in range(m):
		(v, u, d) = lin()
		dept[v] += d
		dept[u] -= d
	ps = []
	mn = []
	for i in range(1, n + 1):
		if dept[i] > 0:
			ps.append([dept[i], i])
		elif dept[i] < 0:
			mn.append([-dept[i], i])
	(i, j) = (0, 0)
	(l1, l2) = (len(ps), len(mn))
	ans = []
	while i < l1 and j < l2:
		if ps[i][0] > mn[j][0]:
			ps[i][0] -= mn[j][0]
			ans.append([ps[i][1], mn[j][1], mn[j][0]])
			j += 1
		elif ps[i][0] == mn[j][0]:
			ans.append([ps[i][1], mn[j][1], mn[j][0]])
			j += 1
			i += 1
		else:
			mn[j][0] -= ps[i][0]
			ans.append([ps[i][1], mn[j][1], ps[i][0]])
			i += 1
	print(len(ans))
	for i in ans:
		print(*i)
main()


import sys
input = sys.stdin.readline
(N, M) = map(int, input().split())
A = [0] * N
for _ in range(M):
	(a, b, d) = map(int, input().split())
	A[a - 1] += d
	A[b - 1] -= d
Plus = []
Minus = []
for i in range(N):
	if A[i] > 0:
		Plus.append((i, A[i]))
	if A[i] < 0:
		Minus.append((i, -A[i]))
ans = []
ind = 0
for (ip, pd) in Plus:
	while pd > 0 and ind < len(Minus):
		(im, md) = Minus[ind]
		if pd >= md:
			ans.append((ip, im, md))
			ind += 1
			pd -= md
		else:
			ans.append((ip, im, pd))
			Minus[ind] = (im, md - pd)
			pd = 0
print(len(ans))
for (p, m, d) in ans:
	print(p + 1, m + 1, d)


(n, m) = map(int, input().split())
A = [0] * (n + 1)
P = []
N = []
for i in range(m):
	(u, v, d) = map(int, input().split())
	A[u] -= d
	A[v] += d
for i in range(1, n + 1):
	if A[i] > 0:
		P.append([A[i], i])
	if A[i] < 0:
		N.append([A[i], i])
i = j = 0
R = []
while i < len(P):
	r = min(P[i][0], -1 * N[j][0])
	R.append([N[j][1], P[i][1], r])
	if r == -1 * N[j][0] == P[i][0]:
		N[j][0] = 0
		P[i][0] = 0
		i += 1
		j += 1
	elif r == P[i][0]:
		N[j][0] += r
		i += 1
	else:
		P[i][0] -= r
		j += 1
print(len(R))
for i in range(len(R)):
	print(R[i][0], R[i][1], R[i][2])


from __future__ import division, print_function

def main():
	import sys
	from io import StringIO as StreamIO
	with StreamIO() as ofs:
		_stdout = sys.stdout
		sys.stdout = ofs
		data = iter(map(int, sys.stdin.buffer.read().decode('ascii').split()))
		(n, m) = (next(data), next(data))
		val = [0] * (n + 1)
		for _ in range(m):
			(u, v, d) = (next(data) for i in range(3))
			val[u] -= d
			val[v] += d
		neg = [(u, -val[u]) for u in range(1, n + 1) if val[u] < 0]
		pos = [(u, val[u]) for u in range(1, n + 1) if val[u] > 0]
		tot = sum((d for (_, d) in pos))
		val = None
		res = []
		while tot:
			left = neg[-1][1]
			right = pos[-1][1]
			if left == 0:
				neg.pop()
				continue
			if right == 0:
				pos.pop()
				continue
			if left > right:
				res.append((neg[-1][0], pos[-1][0], right))
				pos.pop()
				neg[-1] = (neg[-1][0], left - right)
				tot -= right
			else:
				res.append((neg[-1][0], pos[-1][0], left))
				neg.pop()
				pos[-1] = (pos[-1][0], right - left)
				tot -= left
		print(len(res))
		print('\n'.join(('%d %d %d' % (u, v, d) for (u, v, d) in res)))
		sys.stdout = _stdout
		sys.stdout.write(ofs.getvalue())
	return 0
main()


import os, sys, atexit
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
_OUTPUT_BUFFER = StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
(n, m) = [int(x) for x in input().split()]
a = [0] * (n + 1)
for i in range(m):
	(u, v, d) = [int(x) for x in input().split()]
	a[u] -= d
	a[v] += d
neg = []
pos = []
for i in range(1, len(a)):
	if a[i] < 0:
		neg.append([i, -a[i]])
	if a[i] > 0:
		pos.append([i, a[i]])
ans = []
t = 0
for i in range(len(neg)):
	for j in range(t, len(pos)):
		if neg[i][1] <= pos[j][1]:
			if neg[i][1] != 0:
				ans.append([neg[i][0], pos[j][0], neg[i][1]])
			pos[j][1] -= neg[i][1]
			t = j
			break
		else:
			if pos[j][1] != 0:
				ans.append([neg[i][0], pos[j][0], pos[j][1]])
			neg[i][1] -= pos[j][1]
print(len(ans))
for i in ans:
	print(*i)


import sys
import collections
import heapq
import math
import bisect
input = sys.stdin.readline

def rints():
	return map(int, input().strip().split())

def rstr():
	return input().strip()

def rint():
	return int(input().strip())

def rintas():
	return [int(i) for i in input().strip().split()]

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)
(n, m) = rints()
d = [0 for i in range(n)]
for _ in range(m):
	(u, v, k) = rints()
	d[u - 1] += k
	d[v - 1] -= k
ans = []
j = 0
for i in range(n):
	while d[i] > 0:
		while j < n and d[j] >= 0:
			j += 1
		loan = min(d[i], -d[j])
		ans.append((i + 1, j + 1, loan))
		d[i] -= loan
		d[j] += loan
print(len(ans))
for i in ans:
	print(i[0], i[1], i[2])


(n, m) = map(int, input().split())
lst = [0] * (n + 1)
for i in range(m):
	(u, v, d) = map(int, input().split())
	lst[u] -= d
	lst[v] += d
dena = []
dene_wala = []
lena = []
lene_wala = []
for j in range(len(lst)):
	if lst[j] < 0:
		dena.append(abs(lst[j]))
		dene_wala.append(j)
	elif lst[j] > 0:
		lena.append(abs(lst[j]))
		lene_wala.append(j)
l = []
(i, j) = (0, 0)
while i < len(dena):
	while j < len(lena):
		l.append(f'{dene_wala[i]} {lene_wala[j]} {min(dena[i], lena[j])}')
		a = min(dena[i], lena[j])
		dena[i] -= a
		lena[j] -= a
		if lena[j] <= 0:
			j += 1
		if dena[i] <= 0:
			break
	if dena[i] <= 0:
		i += 1
print(len(l))
for k in l:
	print(k)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import defaultdict as dd
I = lambda : list(map(int, input().split()))
(n, m) = I()
fi = [0] * (n + 1)
for i in range(m):
	(u, v, w) = I()
	fi[u] -= w
	fi[v] += w
p = []
m = []
for i in range(1, n + 1):
	if fi[i] < 0:
		m.append([-fi[i], i])
	elif fi[i] > 0:
		p.append([fi[i], i])
an = []
while p and m:
	(a, b) = (p[-1], m[-1])
	if a[0] == b[0]:
		p.pop()
		m.pop()
		an.append([b[1], a[1], a[0]])
	elif a[0] < b[0]:
		m[-1][0] -= a[0]
		p.pop()
		an.append([b[1], a[1], a[0]])
	else:
		p[-1][0] -= b[0]
		m.pop()
		an.append([b[1], a[1], b[0]])
print(len(an))
for (u, v, d) in an:
	print(u, v, d)


import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
graph = []
visited = []
arr = []
ans = []

def main():
	for _ in range(1):
		(n, m) = map(int, input().split())
		arr = [0] * n
		graph = [[] for i in range(n)]
		for i in range(m):
			(u, v, w) = map(int, input().split())
			u -= 1
			v -= 1
			graph[u].append(v)
			arr[u] += w
			arr[v] -= w
		s1 = []
		s2 = []
		for i in range(n):
			if arr[i] > 0:
				s1.append([i, arr[i]])
			elif arr[i] < 0:
				s2.append([i, -arr[i]])
		s1.sort()
		s2.sort()
		ans = []
		while len(s1) and len(s2):
			if s1[-1][1] < s2[-1][1]:
				s2[-1][1] -= s1[-1][1]
				ans.append((s1[-1][0], s2[-1][0], s1[-1][1]))
				s1.pop()
				if s2[-1][1] == 0:
					s2.pop()
			else:
				s1[-1][1] -= s2[-1][1]
				ans.append((s1[-1][0], s2[-1][0], s2[-1][1]))
				s2.pop()
				if s1[-1][1] == 0:
					s1.pop()
		print(len(ans))
		for (u, v, w) in ans:
			print(u + 1, v + 1, w)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import defaultdict
(n, m) = map(int, input().split())
d = defaultdict(int)
for _ in range(m):
	(a, b, c) = map(int, input().split())
	d[a] -= c
	d[b] += c
(neg, pos) = ([], [])
for (k, v) in d.items():
	if v < 0:
		neg.append(k)
	if v > 0:
		pos.append(k)
sol = defaultdict(int)
while neg:
	(x, y) = (neg.pop(), pos.pop())
	if -d[x] > d[y]:
		sol[x, y] += d[y]
		(d[x], d[y]) = (d[x] + d[y], 0)
	else:
		sol[x, y] -= d[x]
		(d[y], d[x]) = (d[x] + d[y], 0)
	if d[x] < 0:
		neg.append(x)
	if d[y] > 0:
		pos.append(y)
print(len(sol))
for (k, v) in sol.items():
	print(k[0], k[1], v)


import sys
zz = 1
sys.setrecursionlimit(10 ** 5)
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

def ii():
	return input().rstrip()

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def gtc(tc, ans):
	print('Case #' + str(tc) + ':', ans)

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j, n, m):
	return 0 <= i < n and 0 <= j < m

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = 1
uu = t
while t > 0:
	t -= 1
	(n, m) = mi()
	debt = [0] * (n + 1)
	for i in range(m):
		(x, y, w) = mi()
		debt[x] += w
		debt[y] -= w
	p = []
	m = []
	for i in range(1, n + 1):
		if debt[i] > 0:
			p.append([debt[i], i])
		else:
			m.append([-debt[i], i])
	ans = []
	i = j = 0
	n = len(p)
	mm = len(m)
	while i < n and j < mm:
		mini = min(p[i][0], m[j][0])
		if mini:
			ans.append([p[i][1], m[j][1], mini])
		p[i][0] -= mini
		m[j][0] -= mini
		if p[i][0] == 0:
			i += 1
		if m[j][0] == 0:
			j += 1
	print(len(ans))
	for i in ans:
		print(*i)


import sys
input = sys.stdin.readline
inf = 100000000000000000
mod = 998244353
(n, m) = map(int, input().split())
B = [0] * n
JIE = []
HUAN = []
for i in range(m):
	(x, y, z) = map(int, input().split())
	x -= 1
	y -= 1
	B[x] += z
	B[y] -= z
for i in range(n):
	if B[i] > 0:
		JIE.append(i)
	elif B[i] < 0:
		HUAN.append(i)
for i in range(len(B)):
	B[i] = abs(B[i])
poshuan = 0
posjie = 0
ANS = []
while posjie < len(JIE) and poshuan < len(HUAN):
	if B[JIE[posjie]] < B[HUAN[poshuan]]:
		ANS.append((JIE[posjie] + 1, HUAN[poshuan] + 1, B[JIE[posjie]]))
		B[HUAN[poshuan]] -= B[JIE[posjie]]
		posjie += 1
	elif B[JIE[posjie]] > B[HUAN[poshuan]]:
		ANS.append((JIE[posjie] + 1, HUAN[poshuan] + 1, B[HUAN[poshuan]]))
		B[JIE[posjie]] -= B[HUAN[poshuan]]
		poshuan += 1
	else:
		ANS.append((JIE[posjie] + 1, HUAN[poshuan] + 1, B[HUAN[poshuan]]))
		poshuan += 1
		posjie += 1
print(len(ANS))
for (aa, bb, cc) in ANS:
	print(aa, bb, cc)


(n, k) = map(int, input().split())
dic = dict()
for _ in range(k):
	(u, v, d) = map(int, input().split())
	if u not in dic:
		dic[u] = -d
	else:
		dic[u] -= d
	if v not in dic:
		dic[v] = d
	else:
		dic[v] += d
dic_neg = dict()
dic_pos = dict()
for (key, value) in dic.items():
	if value > 0:
		dic_pos[key] = value
	elif value < 0:
		dic_neg[key] = value
li_pos = sorted(dic_pos.items(), key=lambda kv: [kv[1], kv[0]], reverse=True)
li_neg = sorted(dic_neg.items(), key=lambda kv: [kv[1], kv[0]])
li_pos = [[key, val] for (key, val) in li_pos]
li_neg = [[key, val] for (key, val) in li_neg]
(pos_ind, neg_ind) = (0, 0)
li = []
while pos_ind != len(li_pos):
	if li_pos[pos_ind][1] >= abs(li_neg[neg_ind][1]):
		li.append([li_neg[neg_ind][0], li_pos[pos_ind][0], abs(li_neg[neg_ind][1])])
		li_pos[pos_ind][1] += li_neg[neg_ind][1]
		li_neg[neg_ind][1] = 0
	else:
		li.append([li_neg[neg_ind][0], li_pos[pos_ind][0], li_pos[pos_ind][1]])
		li_neg[neg_ind][1] += li_pos[pos_ind][1]
		li_pos[pos_ind][1] = 0
	if li_neg[neg_ind][1] == 0:
		neg_ind += 1
	if li_pos[pos_ind][1] == 0:
		pos_ind += 1
print(len(li))
for i in li:
	print(*i)


def main():
	(n, m) = readIntArr()
	balance = [[0, 0, i] for i in range(n + 1)]
	for _ in range(m):
		(u, v, d) = readIntArr()
		balance[u][1] += d
		balance[v][0] += d
	balance.pop(0)
	for i in range(n):
		delta = min(balance[i][0], balance[i][1])
		balance[i][0] -= delta
		balance[i][1] -= delta
	balance.sort(key=lambda x: x[1] - x[0])
	ans = []
	l = 0
	r = n - 1
	while l <= r:
		(lIn, lOut, lI) = balance[l]
		(rIn, rOut, rI) = balance[r]
		if lIn == 0:
			l += 1
			continue
		if rOut == 0:
			r -= 1
			continue
		delta = min(lIn, rOut)
		balance[l][0] -= delta
		balance[r][1] -= delta
		ans.append([rI, lI, delta])
	print(len(ans))
	multiLineArrayOfArraysPrint(ans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultVal, dimensionArr):
	dv = defaultVal
	da = dimensionArr
	if len(da) == 1:
		return [dv for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


from collections import defaultdict
import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
d = defaultdict(int)
for i in range(m):
	(u, v, w) = map(int, input().split())
	d[u] -= w
	d[v] += w
ans = 0
pos = []
neg = []
for i in d.items():
	if i[1] < 0:
		neg.append([i[0], i[1]])
	elif i[1] > 0:
		pos.append([i[0], i[1]])
ans = []
while pos and neg:
	pl = pos.pop()
	nl = neg.pop()
	val = min(pl[1], abs(nl[1]))
	ans.append([nl[0], pl[0], val])
	pl[1] -= val
	nl[1] += val
	if pl[1] != 0:
		pos.append(pl)
	if nl[1] != 0:
		neg.append(nl)
print(len(ans))
for i in ans:
	print(*i)


from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue, copy, time
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
mod = 10 ** 9 + 7
eps = 10 ** (-7)

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_str():
	return list(sys.stdin.readline().split())
(N, M) = inpl()
costs = [0] * N
for _ in range(M):
	(s, t, d) = inpl()
	s -= 1
	t -= 1
	costs[s] += d
	costs[t] -= d
pos = []
neg = []
p = n = 0
for (i, c) in enumerate(costs):
	if c > 0:
		pos.append((c, i))
	elif c < 0:
		neg.append([-c, i])
ni = 0
nL = len(neg)
ans = []
for pi in range(len(pos)):
	(c, s) = pos[pi]
	while c > 0 and ni < nL:
		(n, t) = neg[ni]
		if n == 0:
			ni += 1
			continue
		elif c >= n:
			neg[ni][0] = 0
			ans.append((s + 1, t + 1, n))
			c -= n
			ni += 1
		else:
			neg[ni][0] -= c
			ans.append((s + 1, t + 1, c))
			c = 0
			break
print(len(ans))
print('\n'.join([' '.join(map(str, a)) for a in ans]))


from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')

def main():
	(n, m) = RL()
	gp = [0] * (n + 1)
	for _ in range(m):
		(u, v, d) = RL()
		gp[v] -= d
		gp[u] += d
	pos = [[i + 1, v] for (i, v) in enumerate(gp[1:]) if v > 0]
	neg = [[i + 1, -v] for (i, v) in enumerate(gp[1:]) if v < 0]
	pn = len(pos)
	nn = len(neg)
	pt = nt = 0
	res = []
	while pt < pn and nt < nn:
		if pos[pt][1] == neg[nt][1]:
			res.append([pos[pt][0], neg[nt][0], pos[pt][1]])
			pt += 1
			nt += 1
		elif pos[pt][1] < neg[nt][1]:
			neg[nt][1] -= pos[pt][1]
			res.append([pos[pt][0], neg[nt][0], pos[pt][1]])
			pt += 1
		else:
			pos[pt][1] -= neg[nt][1]
			res.append([pos[pt][0], neg[nt][0], neg[nt][1]])
			nt += 1
	print(len(res))
	for (a, b, c) in res:
		print(a, b, c)
main()


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
(n, m) = [int(x) for x in input().split()]
dp = [0] * (n + 1)
for i in range(m):
	(x, y, z) = [int(x) for x in input().split()]
	if x == y:
		continue
	dp[x] -= z
	dp[y] += z
delta = []
for i in range(n + 1):
	delta.append([dp[i], i])
delta.sort()
i = 0
j = n
res = []
while i < j:
	minn = min(abs(delta[i][0]), abs(delta[j][0]))
	delta[i][0] += minn
	delta[j][0] -= minn
	if minn > 0:
		gamma = [delta[i][1], delta[j][1], minn]
		res.append(gamma)
	if delta[i][0] == 0:
		i += 1
	if delta[j][0] == 0:
		j -= 1
print(len(res))
for i in range(len(res)):
	delta = res[i]
	for j in range(len(delta)):
		print(delta[j], end=' ')
	print('')