n,k=map(int,raw_input().split())
time=[]
al=[]
bo=[]
both=[]
for _ in range(n):
    t,a,b=map(int,raw_input().split())
    if a==1 and b==1:
        both.append(t)
    elif a==1:
        al.append(t)
    elif b==1:
        bo.append(t)
cur1=0
cur2=0
cur3=0
if min(len(al),len(bo))+len(both)<k:
    print -1
else:
    ans=0
    al.sort()
    bo.sort()
    both.sort()
    while k!=0:
        if cur1>=len(al) or cur2>=len(bo) or cur3>=len(both):
            break
        if al[cur1]+bo[cur2]<both[cur3]:
            ans+=al[cur1]+bo[cur2]
            cur1+=1
            cur2+=1
            k-=1
        else:
            ans+=both[cur3]
            cur3+=1
            k-=1
        
    if k!=0:
        if cur1>=len(al) or cur2>=len(bo):
            while k!=0:
                ans+=both[cur3]
                cur3+=1
                k-=1
        else:
            while k!=0:
                ans+=al[cur1]+bo[cur2]
                cur1+=1
                cur2+=1
                k-=1
    print ans

