import collections
def f(s,k):
	both = []
	alice = []
	bob = []
	for ti,ai,bi in s:
		if ai == 1 and bi == 1:
			both.append(ti)
		elif ai == 1 and bi == 0:
			alice.append(ti)
		elif ai == 0 and bi == 1:
			bob.append(ti)
	alice.sort()
	bob.sort()
	both.sort()

	for i in range(1,len(both)):
		both[i] += both[i-1]
	for i in range(1,len(alice)):
		alice[i] += alice[i-1]
	for i in range(1,len(bob)):
		bob[i] += bob[i-1]

	res = +float('inf')
	for i in range(0,len(both)):
		#im taking i+1 books from both
		cost = both[i]
		#I need k - (i+1) from individual
		j = (k - (i + 1)) -1
		if j >= 0:
			if j < len(alice):
				cost += alice[j]
			else:
				cost += float('inf')
		if j >= 0:
			if j < len(bob):
				cost += bob[j]
			else:
				cost += float('inf')
		res = min(res, cost)
	return res if res < float('inf') else -1

	

for t in range(1):
	n,k =  map(int, raw_input().split(' '))
	print f([map(int, raw_input().split()) for _ in range(n)],k)
