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