n,k = map(int,raw_input().split())
both = [];alice = [];bob = []
for _ in range(n):
    t,a,b = map(int,raw_input().split())
    if a==b==1:
        both.append(t)
    elif a==1:
        alice.append(t)
    else:
        bob.append(t)
alice.sort()
bob.sort()
for i in range(min(len(alice),len(bob))):
    both.append(alice[i]+bob[i])
print(-1if len(both)<k else sum(sorted(both)[:k]))
