n,k=tuple(map(int,input().split()))
one1=[]
one2=[]
both=[]
for _ in range(n):
    tmp=list(map(int,input().split()))
    if tmp[1]&tmp[2]:
        both.append(tmp[0])
    elif tmp[1]|tmp[2]:
        if tmp[1]:
            one1.append(tmp[0])
        else:
            one2.append(tmp[0])
if len(both)==0:
    res=-1
else:
    if len(both)>=k:
        both.sort()
        res=sum(both[:k])
    else:
        rem=k-len(both)
        if len(one1)>=rem and len(one2)>=rem:
            one1.sort()
            one2.sort()
            #print(one1,one2)
            res=sum(both)+sum(one1[:k])+sum(one2[:k])
        else:
            res=-1
print(res)
