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


alice.sort(reverse=True)
bob.sort(reverse=True)
both.sort(reverse=True)
total = len(both)
extra = []
while total<k:
    if len(alice)>0 and len(bob)>0:
        extra.append(bob.pop())
        extra.append(alice.pop())
        total+=1
    else:
        print(-1)
        exit(0)
i = len(alice)-1
j = len(bob)-1

for a in range(len(both)):
    if len(alice)==0 or len(bob)==0:
        break
    if both[a] >= alice[-1]+bob[-1]:
        both[a] = 0
        extra.append(bob.pop())
        extra.append(alice.pop())
print(sum(both) + sum(extra))



