import math as mt 
import sys,string
input=sys.stdin.readline
#print=sys.stdout.write
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
from collections import defaultdict



t=1
for _ in range(t):
    n,k=M()
    l=[]
    for i in range(n):
        x,a,b=M()
        l.append((x,a,b))
    l.sort(key=lambda x:((-x[1],-x[2]) or (-x[2],-x[1]),x[0]))
    #print(l)
    a=k
    b=k
    ans=0
    key=0
    for i in range(n):
        if(l[i][1]==1):
            a-=1
        if(l[i][2]==1):
            b-=1
        ans+=l[i][0]
        if(a==0 or b==0):
            key=i
            break
    if(a!=0 and b!=0):
        print(-1)
    else:
        if(a==0 and b==0):
            print(ans)
        else:
            if(a>0):
                #print(a,ans)
                for i in range(key+1,n):
                    if(l[i][1]==1):
                        a-=1
                        ans+=l[i][0]
                    if(a==0):
                        break
                if(a==0):
                    print(ans)
                else:
                    print(-1)
            else:
                for i in range(key+1,n):
                    if(l[i][2]==1):
                        b-=1
                        ans+=l[i][0]
                    if(b==0):
                        break
                if(b==0):
                    print(ans)
                else:
                    print(-1)
    

            
        
            
    
    
    

