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

share=[]
alice=[]
bob=[]

for i in range(n):
	t,a,b=map(int,input().split())
	if a and b:
		share.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
share.sort()
alice.sort()
bob.sort()
if len(share)>=k:
	print(sum(share[:k]))
else:
	m=len(share)
	an=sum(share)
	if len(alice)<k-m or len(bob)<k-m:
		print(-1)
		exit()
	an+=sum(bob[:k-m])+sum(alice[:k-m])
	print(an)