n,k=map(int,input().split())
l,l1,l2=[],[],[]
for i in range(n):
    t,a,b=map(int,input().split())
    if a==1 and b==1:
        l.append(t)
    if a==1 and b==0:
        l1.append(t)
    if a==0 and b==1:
        l2.append(t)
l.sort()
l1.sort()
l2.sort()
c,ans,a,b=0,0,0,0
while a<k or b<k:
    if l and l1 and l2:
        if l[0]<=l1[0]+l2[0]:
            ans+=l.pop(0)
            a+=1
            b+=1
            if a==k:
                l1=[]
            if b==k:
                l2=[]
        else:
            ans+=l1.pop(0)
            ans+=l2.pop(0)
            a+=1
            b+=1
            if a==k:
                l1=[]
            if b==k:
                l2=[]
    elif a<k and l and l1:
        if l[0]>=l1[0]:
            ans+=l.pop(0)
            a+=1
            b+=1
        else:
            ans+=l1.pop(0)
            a+=1
    elif b<k and l and l2:
        if l[0]>=l2[0]:
            ans+=l.pop(0)
            b+=1
            a+=1
        else:
            ans+=l2.pop(0)
            b+=1
    elif l:
        ans+=l.pop(0)
        a+=1
        b+=1
    elif l1:
        ans+=l1.pop(0)
        a+=1
    elif l2:
        ans+=l2.pop(0)
        b+=1
    else:
        c=1
        break
if c==1:
    print(-1)
else:
    print(ans)

    