# f = open('test.py')
# def input():
# 	return f.readline().replace('\n','')

import heapq
import bisect
# from collections import defaultdict
def read_list():
	return list(map(int,input().strip().split(' ')))
def print_list(l):
	print(' '.join(map(str,l)))

def judge_3(n):
	tmp = 0
	for c in str(n):
		tmp+=int(c)
	return tmp%3==0

N,k = read_list()
a,b,c = [],[],[]
for _ in range(N):
	t,x,y = read_list()
	t = -t
	if x==1 and y==1:
		if len(c)<k:
			heapq.heappush(c,t)
		elif t>c[0]:
			heapq.heapreplace(c,t)
	elif x==1:
		if len(a)<k:
			bisect.insort_left(a,t)
		elif t>a[0]:
			a.pop()
			bisect.insort_left(a,t)
	elif y==1:
		if len(b)<k:
			bisect.insort_left(b,t)
		elif t>b[0]:
			b.pop()

			bisect.insort_left(b,t)
if len(c)+min(len(a),len(b))<k:
	print(-1)
else:
	res = sum(c)
	for _ in range(k-len(c)):
		res+=a.pop()
		res+=b.pop()
	while a and b and c and c[0]<b[0]+a[0]:
		res-=c.heappop()
		res+=a.pop()
		res+=b.pop()
	print(-res)

			
	