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

alice = []
bob = []
both = []
for _ in range(n):
    t, a, b = tuple(map(int, input().split()))
    if a == 1 and b == 1:
        both.append(t)
    elif a == 1:
        alice.append(t)
    else:
        bob.append(t)

both.sort()
if k <= len(both):
    result = sum(both[:k])
else:
    remain = k - len(both)
    if remain > len(bob) or remain > len(alice):
        result = -1
    else:
        result = sum(both)
        alice.sort()
        bob.sort()
        result += sum(alice[:remain]) + sum(bob[:remain])
print(result)
