I=lambda: map(int, raw_input().split())
n, k = I()
a = []
b = []
ab = []
for _ in xrange(n):
	t, a1, b1 = I()
	if a1==1 and b1==1:
		ab.append(t)
	elif a1==1:
		a.append(t)
	elif b1==1:
		b.append(t)
ab.sort()
a.sort()
b.sort()
lab = len(ab)
la = len(a)
lb = len(b)
mlalb = min(la, lb)
if lab+mlalb < k:
	print -1
	exit()
s = sum(ab[:k])
q = k-lab
i = 0
while q > 0:
	s += (a[i]+b[i])
	i += 1
	q -= 1
m = s
j = min(lab-1, k-1)
while j >= 0 and i < mlalb:
	s += (a[i]+b[i])
	s -= ab[j]
	j -= 1
	i += 1
	m = min(m, s)
print m