import collections as cc
import math as mt
import sys
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
n,k=I()
a=[]
for i in range(n):
	a.append(I())
a.sort()
both=[]
bs=0
f=0
for i in range(n):
	if a[i][1] and a[i][2]:
		both.append(a[i][0])


al=[]
bo=[]
for i in range(n):
	if a[i][1] and not a[i][2]:
		al.append(a[i][0])
	elif a[i][2] and not a[i][1]:
		bo.append(a[i][0])
su=[]
for i in range(min(len(al),len(bo))):
	su.append(al[i]+bo[i])
for i in range(1,len(both)):
	both[i]+=both[i-1]
for i in range(1,len(su)):
	su[i]+=su[i-1]
if both and not su:
	if len(both)>=k:
		print(both[k-1])
	else:
		print(-1)
elif su and not both:
	if len(su)>=k:
		print(su[k-1])
	else:
		print(-1)
else:
	if len(both)+len(su)<k:
		print(-1)
	elif len(both)<k and len(su)<k:
		xx=k-len(both)
		yy=k-len(su)
		print(min(both[-1]+su[xx-1],su[-1]+both[yy-1]))
	else:
		aa=mt.inf
		bb=mt.inf
		for i in range(len(both)):
			try:
				aa=min(aa,both[i]+su[(k-(i+1))-1])
			except :
				break
		for i in range(len(su)):
			try:
				bb=min(bb,su[i]+both[(k-(i+1))-1])
			except:
				break
		print(min(aa,bb))



