n,k = map(int,input().split())
ali,bob,both=[],[],[]
bothLen,aliLen,bobLen=0,0,0
for i in range(n):
    r,ai,bi = map(int,input().split())
    if ai and bi:
        both.append(r)
        bothLen+=1
    if ai and not bi:
        ali.append(r)
        aliLen+=1
    if bi and not ai:
        bob.append(r)
        bobLen+=1
both.sort(reverse=True)
ali.sort(reverse=True)
bob.sort(reverse=True)
if len(both)+min(aliLen,bobLen)<k:
    print(-1)
else:
    bobs,alice,s = 0,0,0
    for i in range(k):
        if both!=[] and alice<k and bobs<k:
            alice+=1
            bobs+=1
            if ali!=[] and bob!=[]:
                if both[-1]<ali[-1]+bob[-1]:
                    s+=both.pop()
                else:
                    s+=ali.pop()+bob.pop()
            elif ali==[] or bob==[]:
                s+=both.pop()
        elif both!=[] and alice<k:
            alice+=1
            if both[-1]<ali[-1]:
                s+=both.pop()
            else:
                s+=ali.pop()
        elif both!=[] and bobs<k:
            bobs+=1
            if both[-1]<bob[-1]:
                s+=both.pop()
            else:
                s+=bob.pop()
    s+=sum(ali[:k-alice])+sum(bob[:k-bobs])
    print(s)