def books(alice,bob,both,k,n):
    if len(alice)+len(both)<k or len(both)+len(bob)<k:
        return -1
    if n==k :
        return sum(both)+sum(alice)+sum(bob)
    alice=sorted(alice)
    bob=sorted(bob)
    both=sorted(both)
    ac,bc=0,0
    s=0
    while ac<k or bc<k:
        if alice and bob:
            if both and alice[0]+bob[0]>=both[0]:
                ac+=1
                bc+=1
                s+=both.pop(0)
            else:
                ac+=1
                bc+=1
                s+=alice.pop(0)
                s+=bob.pop(0)
        elif alice and bob==[]:
            if both and alice[0]>=both[0]:
                ac+=1
                bc+=1
                s+=both.pop(0)
            elif ac<k:
                ac+=1
                s+=alice.pop(0)
        elif bob and alice==[]:
            if both and bob[0]>=both[0]:
                ac+=1
                bc+=1
                s+=both.pop(0)
            elif bc<k:
                bc+=1
                s+=bob.pop(0)
        if ac<k and alice==[]:
            while ac<k:
                s+=both.pop(0)
                ac+=1
                bc+=1
        if bc<k and bob==[]:
            while bc<k:
                s+=both.pop(0)
                ac+=1
                bc+=1

    return s

a,b,c=[],[],[]
x,y=map(int,input().strip().split())
for i in range(x):
    t,alice,bob=map(int,input().strip().split())
    if alice and bob:
        c.append(t)
    elif alice:
        a.append(t)
    elif bob:
        b.append(t)
print(books(a,b,c,y,x))