from collections import deque
from heapq import heapify, heappop

rr = lambda: input()
rri = lambda: int(input())
rrm = lambda: list(map(int, input().split()))

INF=float('inf')

def solve(N,K,B):
	heap = B
	heapify(heap)
	aread = 0
	soloa = deque()
	bread = 0
	solob = deque()
	totaltime = 0

	while len(heap) > 0 and (aread < K or bread < K):
		time,alike,blike=heappop(heap)
		#print(time,alike,blike)
		#print(soloa, solob)
		#print("!")
		if not alike and not blike:
			continue
		if alike and not blike:
			if aread >= K:
				continue # can't add if exclusive and full
			else:
				aread+=1
				soloa.append(time)
		elif blike and not alike:
			if bread >= K:
				continue # can't add if exclusive and full
			else:
				bread+=1
				solob.append(time)
		else:
			aread += 1
			bread += 1
			totaltime += time
			if aread >= K+1 and len(soloa) > 0:
				soloa.pop()
			if bread >= K+1 and len(solob) > 0:
				solob.pop()

	#print(soloa, solob)
	if aread < K or bread < K:
		return -1
	return totaltime + sum(soloa) + sum(solob)

n,k = rrm()
books = [] # tuples (time, alice likes it, bob likes it)
for _ in range(n):
	time,a,b=rrm()
	books.append((time,a,b))
print(solve(n,k,books))
