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



alice.sort(reverse =True)
alice_co=[i for i in alice]
bob.sort(reverse=True)
bob_co = [i for i in bob]
both.sort(reverse=True)
both_co = [i for i in both]
i=len(both)-1
ans=0
if len(alice)+len(both) <k or len(bob)+len(both)<k:
    print(-1)
else:
    while 1:

        if len(alice)>0 and len(bob)>0 and len(both)>0 and k1!=k and k2!=k:
         
            if alice[-1]+bob[-1]<both[-1]:
                ans += (alice[-1] + bob[-1])
                alice.pop()
                bob.pop()

            else:
                ans += (both[-1])
                both.pop()
            k1+=1
            k2+=1
        else:
            break

    if len(both)==0:
        while len(alice)>0 and k1<k:

            ans+=alice[-1]
            alice.pop()
        while len(bob)>0 and  k2<k:
            ans+=bob[-1]
            bob.pop()

    else:

        ans=0
        if len(alice)==0:

            k1=0
            k2=0
            while 1:

                if len(alice_co) > 0 and len(bob_co) > 0 and len(both_co) > 0 and k1 != k and k2 != k:

                    if alice_co[-1] + bob_co[-1] < both_co[-1]:
                        ans += (alice_co[-1] + bob_co[-1])
                        alice_co.pop()
                        bob_co.pop()

                    else:
                        ans += (both[-1])
                        both_co.pop()
                    k1 += 1
                    k2 += 1
                else:
                    break
            while k1!=k :
                ans+=both_co[-1]
                both_co.pop()
                k1+=1

        else:
            k1 = 0
            while 1:
                if len(alice_co) > 0 and len(bob_co) > 0 and len(both_co) > 0 and k1 != k and k2 != k:
                    if alice_co[-1] + bob_co[-1] < both_co[-1]:
                        ans += (alice_co[-1] + bob_co[-1])
                        alice_co.pop()
                        bob_co.pop()

                    else:
                        ans += (both[-1])
                        both_co.pop()
                    k1 += 1
                    k2 += 1
                else:
                    break
            while k1 != k:
                ans += both_co[-1]
                both_co.pop()
                k1+=1



    print(ans)