n,k=list(map(int,input().split()))
t=[0]*n
a=[-1]*n
b=[-1]*n
ab=[-1]*n
def sortkey(a):
    if a==-1:
        return 10002
    else:
        return t[a]
counta,countb,countab=0,0,0
for i in range(n):
    t[i],a1,b1=list(map(int,input().split()))
    if a1 and b1:
        ab[i]=i
        counta+=1
        countb+=1
        countab+=1
    elif a1:
        a[i]=i
        counta+=1
    elif b1:
        b[i]=i
        countb+=1
    
if counta<k or countb<k:
    print(-1)
else:
    a.sort(key=sortkey)
    b.sort(key=sortkey)
    ab.sort(key=sortkey)
    idex=0
    re=0
    for l in range(min(countab,k)):
        re+=t[ab[l]]
    idex=k-countab
    for l in range(idex):
        re+=t[a[l]]+t[b[l]]
    temp=0
    countab-=1
    while countab>=0 and a[idex]>=0 and b[idex]>=0:
        temp=min(temp,t[a[idex]]+t[b[idex]]-t[ab[countab]])
        countab-=1
        idex+=1
    re+=temp
    print(re)