# from math import log,floor
# from mymodule import input

n,k = map(int,input().split())
l1 = []
l2 = []
for i in range(n):
	a,b,c = map(int,input().split())
	if b!=0:
		l1.append(a)
	if c!=0:
		if b!=0:
			l2.append(2*a)
		else:
			l2.append(a)
if len(l1)>=k and len(l2)>=k:
	l1.sort()
	l2.sort()
	print(max(sum(l1[0:k]),sum(l2[0:k])))
else:
	print(-1)