from sys  import stdin,stdout

import bisect

def st():
    return list(stdin.readline())

def inp():
    return int(stdin.readline())

def li():
    return list(map(int,stdin.readline().split()))

def mp():
    return map(int,stdin.readline().split())

def pr(n):
    stdout.write(str(n)+"\n")

def soe(limit):
    l=[1]*(limit+1)
    prime=[]
    for i in range(2,limit+1):
        if l[i]:
            for j in range(i*i,limit+1,i):
                l[j]=0

    for i in range(2,limit+1):
        if l[i]:
            prime.append(i)
    return prime

def segsoe(low,high):
    limit=int(high**0.5)+1
    prime=soe(limit)
    n=high-low+1
    l=[0]*(n+1)
    for i in range(len(prime)):
        lowlimit=(low//prime[i])*prime[i]
        if lowlimit<low:
            lowlimit+=prime[i]
        if lowlimit==prime[i]:
            lowlimit+=prime[i]
        for j in range(lowlimit,high+1,prime[i]):
            l[j-low]=1
    for i in range(low,high+1):
        if not l[i-low]:
            if i!=1:
                print(i)

def power(a,n):
    r=1
    while n:
        if n&1:
            r=(r*a)
            n=n-1
        else:
            a=(a*a)
            n=n>>1
    return r
    
def solve():
    n,k=mp()
    both=[]
    first=[]
    second=[]
    for i in range(n):
        a,b,c=mp()
        if b==1 and c==1:
            both.append(a)
        elif b==1 and c==0:
            first.append(a)
        elif b==0 and c==1:
            second.append(a)
    if len(both)+len(first)<k or len(both)+len(second)<k:
        pr(-1)
    else:
        
        both.sort()
        first.sort()
        second.sort()
        i,j,z=0,0,0
        p=0
        while k!=0:
            if z<len(both):
                temp=both[z]
            else:
                temp=float("inf")
            if i<len(first):
                temp1=first[i]
            else:
                temp1=float("inf")
            if j<len(second):
                temp2=second[j]
            else:
                temp2=float("inf")

            if temp<=temp1+temp2:
                p+=temp
                z+=1
            else:
                p+=temp1+temp2
                i+=1
                j+=1
            k-=1
        print(p)
            

solve()
##
##for _ in range(inp()):
##    solve()
    
