import atexit, io, sys 
  
# A stream implementation using an in-memory bytes  
# buffer. It inherits BufferedIOBase. 
buffer = io.BytesIO() 
sys.stdout = buffer
  
# print via here 
@atexit.register 
def write(): 
    sys.__stdout__.write(buffer.getvalue())

for _ in range(1):
    n,k=map(int,raw_input().split())
    v=[]
    t=[]
    for i in range(n):

        vc=map(int,raw_input().split())
        if vc[1] or vc[2]:
            v.append(vc)
    s=sorted(v)
    ac,bc,at,bt=0,0,0,0
    a,b=[],[]
    for i in v:
        if i[1]!=1 or i[2]!=1:
            if i[1]==1:
                ac+=1
                a.append(i[0])
            else:
                bc+=1
                b.append(i[0])
        else:
            t.append(i[0])
    
    if len(t)>=k:
        p,g=0,k-1
        ca=sum(t[:k])
        
        while( p<len(a) and p<len(b) and g>=0):
            if (a[p]+b[p])<=t[g]:
                ca=ca-t[g]+a[p]+b[p];p+=1;g-=[1]
            else:
                break
        print ca
    elif( len(a)+len(t))<k or (len(b)+len(t)) <k:
        print -1;continue
        
    else :
        f=k-len(t)
        h=k-len(t)
        ca=sum(a[:f])+sum(b[:f])+sum(t)
        p,g=f,k-1
        
        
        while( p<len(a) and p<len(b) and g>=0):
            if (a[p]+b[p])<=t[g]:
                ca=ca-t[g]+a[p]+b[p];p+=1;g-=[1]
            else:
                break
        print ca
        