k, n = [int(i) for i in input().split()]


a = []
b = []
both = []
for _ in range(k):
	t,x,y = [int(i) for i in input().split()]

	if(x == 1 and y == 1):
		both.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)

a.sort()
b.sort()
both.sort()
# print(a,b,both)

aCount = 0
bCount = 0
T = 0
while(aCount != n):
	if len(a) != 0 and len(both) != 0:
		if(both[0] <= a[0]):
			aCount+=1
			bCount+=1
			T+=both[0]
			del both[0]
		else:
			aCount+=1
			T+=a[0]
			del a[0]
	elif len(a) != 0:
		aCount+=1
		T+=a[0]
		del a[0]
	elif len(both) != 0:
		aCount+=1
		bCount+=1
		T+=both[0]
		del both[0]
	else:
		print(-1)
		quit()

while(bCount != n):
	if len(b) != 0 and len(both) != 0:
		if(both[0] <= b[0]):
			aCount+=1
			bCount+=1
			T+=both[0]
			del both[0]
		else:
			aCount+=1
			T+=b[0]
			del b[0]
	elif len(b) != 0:
		bCount+=1
		T+=b[0]
		del b[0]
	elif len(both) != 0:
		aCount+=1
		bCount+=1
		T+=both[0]
		del both[0]
	else:
		print(-1)
		quit()
print(T)


