n,k = map(int,input().split())

Both = []
Alice = []
Bob = []
for i in range(n):

	t,a,b = map(int,input().split())

	if a == 1 and b == 1:
		Both.append(t)
	elif a == 1:
		Alice.append(t)
	elif b == 1:
		Bob.append(t)

Both.sort()

Alice.sort()

Bob.sort()

# print(Both)
# print(Bob)
i = 0
# print(Alice)
act_read = []
# if len(Aice)
if len(Alice) < k:
	# i = 0
	r = k - len(Alice)
	while i < r:
		act_read.append(Both[i])
		i = i + 1

if len(Bob) < k:
	r = k - len(Bob)
	j = 0
	while j < r and i < len(Bob):
		act_read.append(Both[i])
		# Bob.append(Both[i])
		i = i + 1
		j = j + 1
Both = Both[i:]

Alice.sort()
Bob.sort()
Both = Both[i:]
# d[a] = len(act_read)
# d[b] = len(act_read)
while len(act_read) < k and i < len(Both) and j < len(Alice) and k < len(Bob):

	if Both [i] <= Alice[j] + Bob[k]:
		act_read.append(Both[i])
		i = i + 1
	else:
		act_read.append(Alice[j]+Bob[k])
		j = j + 1
		k = k + 1
print(sum(act_read))