n,k=map(int,input().split())
l=[]
for i in range(0,n):
    l1=list(map(int,input().split()))
    l.append(l1)
alice=[]
l.sort()
bob=[]
for i in range(0,n):
    if(l[i][1]==1):
        alice.append(l[i][0])
    if(l[i][2]==1):
        bob.append(l[i][0])
alice.sort()
bob.sort()
if(len(alice)<k or len(bob)<k):
    print(-1)
else:
    l2=[]
    sum1=sum(alice[0:k])+sum(bob[0:k])
    m=bob[0:k]
    for i in range(0,k):
        if(alice[i] in m):
            sum1=sum1-alice[i]
            m.remove(alice[i])
            
    sum2=0
    a=0
    inter=0
    for i in range(0,n):
        if(inter==k):
            break
        if(l[i][0] in alice and l[i][0] in bob):
            sum2+=l[i][0]
            alice.remove(l[i][0])
            bob.remove(l[i][0])
            inter+=1
        if(inter==k):
            break
    print(l2,k)
    alice.sort()
    bob.sort()
    if(inter<k):
        sum2+=sum(alice[0:(k-inter)])+sum(bob[0:(k-inter)])
    print(min(sum1,sum2))
        
