n,k = map(int, input().split())

a = []
b = []
comman = []

for _ in range(n):
	t,ai,bi = map(int, input().split())
	if ai == 1:
		a.append(t)
	if bi == 1:	
		b.append(t)
	if ai == 1 and bi == 1:
		comman.append(t)

a.sort()
b.sort()
comman.sort()

if len(a) < k or len(b) < k:
	print(-1)

else:
	s = 0
	ki = k
	for i in range(k):
		s += a[i]
		if a[i] in comman:
			b.remove(a[i])
			comman.remove(a[i])
			ki -= 1

	for i in range(ki):
		s += b[i]

	print(s)







