import math
n,k=map(int,input().split())
books=[]
a=[]
b=[]
for i in range(0,n):
    l=list(map(int,input().split()))
    books.append(l)
alice=0
bob=0
for i in range(0,n):
    if(books[i][1]==1):
        a.append(books[i][0])
    if(books[i][2]==1):
        b.append(books[i][0])
if(len(a)<k or len(b)<k):
    print(-1)
else:
    a.sort()
    b.sort()
    m=[]
    sum=0
    for i in a:
        if(alice==k):
            break
        sum+=i
        m.append(i)
        alice+=1
        if(i in b):
            bob+=1
    for i in b:
        if(bob==k):
            break
        if(i in m):
            continue
        sum+=i
        bob+=1
    print(sum)
        
        
    

        
