# reading_books.py
from collections import defaultdict
n,k = map(int,input().split())
time = [] 
alice = [] 
bob = []
my_dick = {}
my_dick = defaultdict(lambda:list(),my_dick)
for i in range(n):
	a,b,c = map(int,input().split())
	if b+c==2:
		my_dick[b+c].append(a)
	elif b==0 and c == 1:
		my_dick[b+3].append(a)
	elif c==0 and b == 1:
		my_dick[c+4].append(a)

if len(my_dick[2])>=k:
	my_dick[2] = sorted(my_dick[2])
	# ans = 
	# ans = 0
	# k = k-len(my_dick[2])
	if len(my_dick[3])>=k and len(my_dick[4])>=k:
		print(max(sum(sorted(my_dick[3][:k])) + sum(sorted(my_dick[4][:k]))),sum(my_dick[2][:k]))
	print()
else:
	ans = sum(my_dick[2])
	k = k-len(my_dick[2])
	if len(my_dick[3])>=k and len(my_dick[4])>=k:
		print(ans + sum(sorted(my_dick[3][:k])) + sum(sorted(my_dick[4][:k])))
	else:
		print("-1")