# cook your dish here
a,b=map(int,input().split())
s=0
k=0
p=[]
q=[]
for _ in range(a):
    # k=b
    x,y,z=map(int,input().split())
    if(k!=b and y==1 and z==1):
        s=s+x
        k+=1
    elif(y==1 and z==0):
        p.append(x)
    elif(y==0 and z==1):
        q.append(x)
if(k!=b):
    if(len(p)<b-k or len(q)<b-k):
        print("-1")
    else:
        p.sort()
        q.sort()
        for i in range(b-k):
            s=s+p[i]+q[i]
        print(s)
else:
    print(s)
    
    
    
        