

def main():
    n,k=map(int,input().split())
    al=[]
    bob=[]
    comb=[]
    for i in range(n):
        x,y,z=map(int,input().split())
        if y==1 and z==1:
            comb.append(x)
        if y==1 and z==0:
            al.append(x)
        if z==1 and y==0:
            bob.append(x)
    comb_len=len(comb)
    bob_len=len(bob)
    al_len=len(al)
    if al_len+comb_len<k or bob_len+comb_len<k:
        print(-1)
        exit()
    al.sort()
    bob.sort()
    comb.sort()
    if comb_len>=k:
        ans=sum(comb[:k])
    else:
        ans=sum(comb)+sum(al[:k-comb_len])+sum(bob[:k-comb_len])
        
        
    print(ans)
        
    
    
        
    
       
main()
