import sys
import math as mt
input=sys.stdin.buffer.readline  
t=1
def Sort(sub_li): 
   
    sub_li.sort(key = lambda x: x[0]) 
    return sub_li 
#t=int(input())
for _ in range(t):
    #n=int(input())
    n,k=map(int,input().split())
    #l=list(map(int,input().split()))
    l2=[]
    for ___ in range(n):
        time,a,b=map(int,input().split())
        l2.append([time,a,b])
    l1=Sort(l2)
    #print(l1)
    ans=0
    k1,k2=k,k
    res=[]
    rem1=[]
    rem2=[]
    tot1,tot2=0,0
    for i in range(n):
        if l1[i][1]==1:
            tot1+=1
        if l1[i][2]==1:
            tot2+=1
    occ1,occ2=0,0
    for i in range(n):
        if l1[i][1]!=l1[i][2]:
            
            if l1[i][1]==1:
                if k1>0:
                    occ1+=1
                    res.append([l1[i][0],1,0])
                    k1-=1
                    ans+=l1[i][0]
            else:
                if k2>0:
                    occ2+=1
                    res.append([l1[i][0],0,1])
                    k2-=1
                    ans+=l1[i][0]
        else:
            if l1[i][1]==l1[i][2] and l1[i][1]==1:
                if len(res)>=2:
                    rem1=((tot1-occ1+(res[-1][1]+res[-2][1])))
                    rem2=((tot2-occ2+(res[-1][2]+res[-2][2])))
                    rem3=(tot1-occ1)
                    rem4=(tot2-occ2)
                    #print(120,res)
                    #print(121,i,rem1,k1,rem2,k2,rem3,rem4)
                    if (rem1<k1 or rem2<k2):
                        if k1>0:
                            occ1+=1
                        if k2>0:
                            occ2+=1
                        k1=max(k1-1,0)
                        k2=max(k2-1,0)
                        ans+=l1[i][0]
                    else:    
                        if ((res[-1][0]+res[-2][0])>=l1[i][0] and rem1>=k1 and rem2>=k2):
                            #print(11,i)
                            #occ1-=(res[-1][1]+res[-2][1])
                            #occ2-=(res[-1][2]+res[-2][2])
                            if k1>0:
                                occ1+=1
                            if k2>0:
                                occ2+=1
                            ans-=(res[-1][0]+res[-2][0])
                            k1=max(k1-1,0)
                            k2=max(k2-1,0)
                            occ1+=1
                            occ2+=1
                            ans+=l1[i][0]
                            res.pop()
                            res.pop()
                else:
                    if k1>0 or k2>0:
                        ans+=l1[i][0]
                        k1=max(k1-1,0)
                        k2=max(k2-1,0)
                            
                            
                    
    if k1>0 or k2>0:
        print(-1)
    else:    
        print(ans)                    