You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer $n$ castles of your opponent.

Let's describe the game process in detail. Initially you control an army of $k$ warriors. Your enemy controls $n$ castles; to conquer the $i$-th castle, you need at least $a_i$ warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army — formally, after you capture the $i$-th castle, $b_i$ warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter $c_i$, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:

  if you are currently in the castle $i$, you may leave one warrior to defend castle $i$;  there are $m$ one-way portals connecting the castles. Each portal is characterised by two numbers of castles $u$ and $v$ (for each portal holds $u > v$). A portal can be used as follows: if you are currently in the castle $u$, you may send one warrior to defend castle $v$. 

Obviously, when you order your warrior to defend some castle, he leaves your army.

You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle $i$ (but only before capturing castle $i + 1$) you may recruit new warriors from castle $i$, leave a warrior to defend castle $i$, and use any number of portals leading from castle $i$ to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle $i$ won't be available to you.

If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it — your score will be calculated afterwards).

Can you determine an optimal strategy of capturing and defending the castles?


-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($1 \le n \le 5000$, $0 \le m \le \min(\frac{n(n - 1)}{2}, 3 \cdot 10^5)$, $0 \le k \le 5000$) — the number of castles, the number of portals and initial size of your army, respectively.

Then $n$ lines follow. The $i$-th line describes the $i$-th castle with three integers $a_i$, $b_i$ and $c_i$ ($0 \le a_i, b_i, c_i \le 5000$) — the number of warriors required to capture the $i$-th castle, the number of warriors available for hire in this castle and its importance value.

Then $m$ lines follow. The $i$-th line describes the $i$-th portal with two integers $u_i$ and $v_i$ ($1 \le v_i < u_i \le n$), meaning that the portal leads from the castle $u_i$ to the castle $v_i$. There are no two same portals listed.

It is guaranteed that the size of your army won't exceed $5000$ under any circumstances (i. e. $k + \sum\limits_{i = 1}^{n} b_i \le 5000$).


-----Output-----

If it's impossible to capture all the castles, print one integer $-1$.

Otherwise, print one integer equal to the maximum sum of importance values of defended castles.


-----Examples-----
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3

Output
5

Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1

Output
22

Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3

Output
-1



-----Note-----

The best course of action in the first example is as follows:

  capture the first castle;  hire warriors from the first castle, your army has $11$ warriors now;  capture the second castle;  capture the third castle;  hire warriors from the third castle, your army has $13$ warriors now;  capture the fourth castle;  leave one warrior to protect the fourth castle, your army has $12$ warriors now. 

This course of action (and several other ones) gives $5$ as your total score.

The best course of action in the second example is as follows:

  capture the first castle;  hire warriors from the first castle, your army has $11$ warriors now;  capture the second castle;  capture the third castle;  hire warriors from the third castle, your army has $13$ warriors now;  capture the fourth castle;  leave one warrior to protect the fourth castle, your army has $12$ warriors now;  send one warrior to protect the first castle through the third portal, your army has $11$ warriors now. 

This course of action (and several other ones) gives $22$ as your total score.

In the third example it's impossible to capture the last castle: you need $14$ warriors to do so, but you can accumulate no more than $13$ without capturing it.

Source: codeforces | Difficulty: HARD
Tags: Sorting

Implementation

Greedy algorithms

Dynamic programming

Data structures


Solutions:
import sys
input = sys.stdin.readline
import heapq as hp

def main():
	(N, M, K) = map(int, input().split())
	ABC = [list(map(int, input().split())) for _ in range(N)]
	Tmp = [i for i in range(N)]
	for _ in range(M):
		(a, b) = map(int, input().split())
		Tmp[b - 1] = max(Tmp[b - 1], a - 1)
	Val = [[] for _ in range(N)]
	for (i, (_, _, c)) in enumerate(ABC):
		Val[Tmp[i]].append(c)
	q = []
	S = K
	for (i, (a, b, _)) in enumerate(ABC):
		vacant = S - a
		if vacant < 0:
			return -1
		while len(q) > vacant:
			hp.heappop(q)
		S += b
		for p in Val[i]:
			hp.heappush(q, p)
	while len(q) > S:
		hp.heappop(q)
	return sum(q)
print(main())


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
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=300006, 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, 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 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, k) = map(int, input().split())
l = []
N = 5005
for i in range(n):
	(a, b, c) = map(int, input().split())
	l.append((a, b, c))
d = defaultdict(list)
w = defaultdict(int)
sw = set()
for i in range(m):
	(a, b) = map(int, input().split())
	sw.add(b)
	w[b] = max(w[b], a)
for i in w:
	d[w[i]].append(i)
dp = [[-30000000 for j in range(N)] for i in range(n + 1)]
dp[0][k] = 0
for i in range(1, n + 1):
	for j in range(N):
		t = l[i - 1][0]
		t1 = l[i - 1][1]
		if 0 <= j + t1 < N and j >= t:
			dp[i][j + t1] = max(dp[i][j + t1], dp[i - 1][j])
			if i not in sw and 0 <= j + t1 - 1 < N:
				dp[i][j + t1 - 1] = max(dp[i][j + t1 - 1], dp[i - 1][j] + l[i - 1][2])
	for t in d[i]:
		for j in range(N):
			if 0 <= j - 1 < N:
				dp[i][j - 1] = max(dp[i][j - 1], dp[i][j] + l[t - 1][2])
ans = -99999999999
for i in range(N):
	ans = max(ans, dp[-1][i])
if ans < 0:
	print(-1)
else:
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
MX = 5001
(n, m, k) = map(int, input().split())
xyz = []
for _ in range(n):
	(x, y, z) = map(int, input().split())
	xyz.append((x, y, z))
graph = [[] for _ in range(n)]
mx_list = [0] * n
for _ in range(m):
	(u, v) = map(int, input().split())
	if mx_list[v - 1] < u - 1:
		mx_list[v - 1] = u - 1
for (v, u) in enumerate(mx_list):
	if u > 0:
		graph[u].append(v)
no_portal = {i for (i, j) in enumerate(mx_list) if j == 0}
dp = [-1] * MX
dp[k] = 0
for i in range(n):
	(x, y, z) = xyz[i]
	newdp = [-1] * MX
	li = []
	if i in no_portal:
		li.append(z)
	for to in graph[i]:
		li.append(xyz[to][2])
	li.sort(reverse=True)
	for j in range(len(li) - 1):
		li[j + 1] += li[j]
	li = [0] + li
	for j in range(x, MX - y):
		if dp[j] < 0:
			continue
		for l in range(len(li)):
			if j + y - l < 0:
				break
			if newdp[j + y - l] < dp[j] + li[l]:
				newdp[j + y - l] = dp[j] + li[l]
	dp = newdp
print(max(dp))


import sys
input = sys.stdin.buffer.readline
(N, M, K) = map(int, input().split())
A = [0] * N
B = [0] * N
C_raw = [0] * N
for i in range(N):
	(A[i], B[i], C_raw[i]) = map(int, input().split())
adj = [[] for _ in range(N + 1)]
for _ in range(M):
	(u, v) = map(int, input().split())
	adj[v].append(u)
C = [[] for _ in range(N)]
for i in range(N):
	if adj[i + 1]:
		C[max(adj[i + 1]) - 1].append(C_raw[i])
	else:
		C[i].append(C_raw[i])
for i in range(N):
	if C[i]:
		C[i].sort(reverse=True)
dp = [[-10 ** 5] * 5001 for _ in range(N + 1)]
dp[0][K] = 0
for i in range(N):
	for k in range(5001):
		if dp[i][k] >= 0:
			if k >= A[i]:
				dp[i + 1][k + B[i]] = max(dp[i + 1][k + B[i]], dp[i][k])
				p = k + B[i]
				q = 0
				cnt = 0
				for ci in C[i]:
					if p > 0:
						p -= 1
						q += ci
						cnt += 1
						dp[i + 1][k + B[i] - cnt] = max(dp[i + 1][k + B[i] - cnt], dp[i][k] + q)
					else:
						break
if max(dp[-1]) >= 0:
	print(max(dp[-1]))
else:
	print(-1)


import os, sys
from io import BytesIO, IOBase

class SortedList:

	def __init__(self, iterable=None, _load=200):
		if iterable is None:
			iterable = []
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def main():
	(n, m, k) = map(int, input().split())
	(req, inc, imp) = ([], [], [])
	for _ in range(n):
		(a1, b1, c1) = map(int, input().split())
		req.append(a1)
		inc.append(b1)
		imp.append(c1)
	path = [[] for _ in range(n)]
	for _ in range(m):
		(u1, v1) = map(int, input().split())
		path[u1 - 1].append(v1 - 1)
	(excess, si) = ([0] * n, k)
	for i in range(n):
		if req[i] > si:
			return -1
		si += inc[i]
		excess[i] = si - req[i + 1] if i != n - 1 else si
	for i in range(n - 2, -1, -1):
		excess[i] = min(excess[i], excess[i + 1])
	(curr, visi, ans) = (SortedList(), [0] * n, 0)
	for i in range(n - 1, -1, -1):
		if not visi[i]:
			visi[i] = i
			curr.add(imp[i])
		for j in path[i]:
			if not visi[j]:
				visi[j] = i
				curr.add(imp[j])
		for _ in range(excess[i] - (0 if not i else excess[i - 1])):
			if len(curr):
				ans += curr.pop()
			else:
				break
	return ans
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')
print(main())


import sys
input = sys.stdin.readline
(n, m, k) = map(int, input().split())
cas = [list(map(int, input().split())) for i in range(n)]
pot = [list(map(int, input().split())) for i in range(m)]
timing = [i for i in range(n)]
for i in range(m):
	(a, b) = pot[i]
	a -= 1
	b -= 1
	if a > b:
		(a, b) = (b, a)
	timing[a] = max(b, timing[a])
time = [[] for i in range(n)]
for i in range(n):
	time[timing[i]].append(cas[i][2])
for i in range(n):
	time[timing[i]].sort(reverse=True)
memo = {}
memo[k] = 0
for i in range(n):
	(a, add_, c) = cas[i]
	memo2 = {}
	for j in memo:
		if j >= a:
			memo2[j + add_] = memo[j]
	for num in time[i]:
		tmp = memo2.copy()
		for j in tmp:
			if j - 1 not in memo2:
				memo2[j - 1] = tmp[j] + num
			else:
				memo2[j - 1] = max(tmp[j - 1], tmp[j] + num)
	memo = memo2.copy()
ans = -1
for i in memo:
	ans = max(ans, memo[i])
print(ans)


from heapq import heappush, heappop
(n, m, k) = map(int, input().split())
a = [0]
b = [0]
c = [0]
for i in range(n):
	(aa, bb, cc) = map(int, input().split())
	a.append(aa)
	b.append(bb)
	c.append(cc)
a += [0]
road = [[] for i in range(n + 1)]
last = [i for i in range(0, n + 1)]
for i in range(m):
	(u, v) = map(int, input().split())
	last[v] = max(last[v], u)
for i in range(1, n + 1):
	road[last[i]].append(i)
value = []
fin = True
for i in range(1, n + 1):
	while k < a[i] and value:
		k += 1
		heappop(value)
	if k < a[i]:
		fin = False
		break
	k += b[i]
	for j in road[i]:
		heappush(value, c[j])
		k -= 1
if fin == False:
	print(-1)
else:
	while k < 0:
		k += 1
		heappop(value)
	ans = 0
	while value:
		ans += heappop(value)
	print(ans)


from sys import stdin, stdout
from collections import namedtuple, deque
from bisect import insort
Castle = namedtuple('Castle', ['defense', 'recruit', 'importance'])
(n, m, k) = map(int, stdin.readline().split())
castles = []
portals = {}
for i in range(n):
	(a, b, c) = map(int, stdin.readline().split())
	castles.append(Castle(a, b, c))
	portals[i] = -1
for _ in range(m):
	(u, v) = map(int, stdin.readline().split())
	if u > v and u - 1 > portals[v - 1]:
		portals[v - 1] = u - 1
defending = deque()
pending = deque()
score = 0
for (i, c) in enumerate(castles):
	while k < c.defense and defending:
		v = defending.popleft()
		score -= v
		k += 1
	if k < c.defense:
		score = -1
		break
	k += c.recruit
	while pending and pending[0][0] == i:
		(_, v) = pending.popleft()
		k -= 1
		score += v
		insort(defending, v)
	if portals[i] < 0:
		k -= 1
		insort(defending, c.importance)
		score += c.importance
	else:
		insort(pending, (portals[i], c.importance))
else:
	while k < 0:
		v = defending.popleft()
		k += 1
		score -= v
stdout.write('{}\n'.format(score))


import sys
(n, m, k) = map(int, input().split())
castle = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
_p = [[] for _ in range(n)]
endpoints = [0] * n
for (u, v) in (map(int, l.split()) for l in sys.stdin):
	_p[v - 1].append(u - 1)
	endpoints[v - 1] = 1
portal = [[] for _ in range(n)]
for t in range(n):
	if _p[t]:
		s = max(_p[t])
		portal[s].append(castle[t][2])
max_n = 5000
dp = [-1] * (max_n + 1)
dp[k] = 0
for (i, (a, b, c)) in enumerate(castle):
	next_dp = [-1] * (max_n + 1)
	p = portal[i]
	if not endpoints[i]:
		p.append(c)
	p.sort(reverse=True)
	for i in range(len(p) - 1):
		p[i + 1] += p[i]
	p = [0] + p
	len_p = len(p)
	for i in range(a, max_n - b + 1):
		if dp[i] == -1:
			continue
		w = i + b
		for j in range(len_p):
			next_dp[w - j] = max(next_dp[w - j], dp[i] + p[j])
			if w - j == 0:
				break
	dp = next_dp
print(max(dp))


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

class RAQ_RMQ:

	def __init__(self, n, inf=2 ** 31 - 1):
		self.n0 = 1 << (n - 1).bit_length()
		self.INF = inf
		self.data = [0] * (2 * self.n0)
		self.lazy = [0] * (2 * self.n0)

	def getIndex(self, l, r):
		l += self.n0
		r += self.n0
		lm = l // (l & -l) >> 1
		rm = r // (r & -r) >> 1
		while l < r:
			if r <= rm:
				yield r
			if l <= lm:
				yield l
			l >>= 1
			r >>= 1
		while l:
			yield l
			l >>= 1

	def propagates(self, *ids):
		for i in reversed(ids):
			v = self.lazy[i - 1]
			if not v:
				continue
			self.lazy[2 * i - 1] += v
			self.lazy[2 * i] += v
			self.data[2 * i - 1] += v
			self.data[2 * i] += v
			self.lazy[i - 1] = 0

	def update(self, l, r, x):
		(*ids,) = self.getIndex(l, r)
		l += self.n0
		r += self.n0
		while l < r:
			if r & 1:
				r -= 1
				self.lazy[r - 1] += x
				self.data[r - 1] += x
			if l & 1:
				self.lazy[l - 1] += x
				self.data[l - 1] += x
				l += 1
			l >>= 1
			r >>= 1
		for i in ids:
			self.data[i - 1] = min(self.data[2 * i - 1], self.data[2 * i]) + self.lazy[i - 1]

	def query(self, l, r):
		self.propagates(*self.getIndex(l, r))
		l += self.n0
		r += self.n0
		s = self.INF
		while l < r:
			if r & 1:
				r -= 1
				s = min(s, self.data[r - 1])
			if l & 1:
				s = min(s, self.data[l - 1])
				l += 1
			l >>= 1
			r >>= 1
		return s
(n, m, k) = map(int, input().split())
l = [0] * (n + 1)
now = k
point = [0] * n
for i in range(n):
	(a, b, c) = map(int, input().split())
	point[i] = c
	now = now - a
	l[i] = now
	now += b + a
l[n] = now
RMQ = RAQ_RMQ(n + 1)
for i in range(n + 1):
	RMQ.update(i, i + 1, l[i])
portal = list(range(n))
for i in range(m):
	(u, v) = map(int, input().split())
	(u, v) = (u - 1, v - 1)
	if portal[v] < u:
		portal[v] = u
if RMQ.query(0, n + 1) < 0:
	print(-1)
	return
heap = [(-point[i], -portal[i]) for i in range(n)]
from heapq import heapify, heappop
heapify(heap)
ans = 0
while heap:
	(p, i) = heappop(heap)
	(p, i) = (-p, -i)
	if RMQ.query(i + 1, n + 1) > 0:
		ans += p
		RMQ.update(i + 1, n + 1, -1)
print(ans)


import sys
from heapq import heappush, heappop
reader = (map(int, line.split()) for line in sys.stdin)
(n, m, k) = next(reader)
castle = [list(next(reader)) for _ in range(n)]
last = [i for i in range(n)]
for _ in range(m):
	(u, v) = next(reader)
	u -= 1
	v -= 1
	last[v] = max(last[v], u)
portal = [[] for _ in range(n)]
for (v, u) in enumerate(last):
	portal[u].append(v)
queue = []
possible = True
for (i, (a, b, c)) in enumerate(castle):
	while k < a and queue:
		k += 1
		heappop(queue)
	if k < a:
		possible = False
		break
	k += b
	for v in portal[i]:
		k -= 1
		heappush(queue, castle[v][2])
if not possible:
	print(-1)
else:
	while k < 0:
		heappop(queue)
		k += 1
	sum_cost = 0
	while queue:
		sum_cost += heappop(queue)
	print(sum_cost)


import sys
input = sys.stdin.readline
from collections import *
(n, m, k) = map(int, input().split())
(a, b, c) = ([], [], [])
for _ in range(n):
	(ai, bi, ci) = map(int, input().split())
	a.append(ai)
	b.append(bi)
	c.append(ci)
now = k
for i in range(n):
	if now < a[i]:
		print(-1)
		exit()
	now += b[i]
G = [[] for _ in range(n)]
for _ in range(m):
	(u, v) = map(int, input().split())
	G[u - 1].append(v - 1)
last = [-1] * n
flag = [False] * n
for i in range(n - 1, -1, -1):
	if not flag[i]:
		last[i] = i
		flag[i] = True
	for j in G[i]:
		if not flag[j]:
			last[j] = i
			flag[j] = True
ic = [(i, c[i]) for i in range(n)]
ic.sort(key=lambda t: t[1], reverse=True)
ans = 0
decre = [0] * n
for (i, ci) in ic:
	now = k
	decre[last[i]] += 1
	flag = False
	for j in range(n):
		if now < a[j]:
			decre[last[i]] -= 1
			flag = True
			break
		now += b[j]
		now -= decre[j]
	if flag:
		continue
	elif now < 0:
		decre[last[i]] -= 1
	else:
		ans += ci
print(ans)