n,k=map(int,input().split())
p1=[]
a1=[]
b1=[]
c1=0
for _ in range(n):
    p,a,b=map(int,input().split())
    if(a==1 and b==1):
        p1.append(p)
        c1+=1
    elif(a==1):
        a1.append(p)
    elif( b==1):
        b1.append(p)
a1.sort()
b1.sort()
p1.sort()
s=sum(p1)
if(c1==k):
    print(s)
elif(len(p1)>k):
    print(sum(p1[:k]))
elif(c1+len(a1)< k or c1+len(b1)<k ):
    print(-1)
else:
    for i in range(k-c1):
        s+=a1[i]+b1[i]
    print(s)