n,k = map(int, input().split())
A = set()
B = set()
arr = []
for i in range(n):
	t,a,b = map(int, input().split())
	arr.append(t)
	if (a==1):
		A.add(i)
	if (b==1):
		B.add(i)
if (len(A)>=k and len(B)>=k):
	inter = A.intersection(B)
	if (len(inter)>=k):
		inter = list(inter)
		for i in range(len(inter)):
			inter[i] = arr[inter[i]]
		inter.sort()
		print(sum(inter[:k]))
	else:
		cost = 0
		a = list(A.difference(inter))
		b = list(B.difference(inter))
		for i in range(len(a)):
			a[i] = arr[a[i]]
		for i in range(len(b)):
			b[i] = arr[b[i]]
		a.sort()
		b.sort()
		cost += sum(a[:k-len(inter)])
		cost += sum(b[:k-len(inter)])
		inter = list(inter)
		for i in range(len(inter)):
			cost += arr[inter[i]]
		print(cost)
else:
	print(-1)