# cook your dish here
n,k=map(int,input().split())
a=[0 for i in range(n)]
b=[0 for i in range(n)]
x=[]
cnta=0
cntb=0
for i in range(n):
    t,p,q=list(map(int,input().split()))
    
    t=[t,p,q]
    x.append(t)
x.sort()
for i in range(n):
    t,p,q=x[i]
    if p:
        a[i]=1
        cnta+=1
    if q:
        b[i]=1
        cntb+=1
    #t=[t,p,q]
    #x.append(t)
#print(x)
if cnta>=k and cntb>=k:
    out=0
    ac=0
    bc=0
    if cnta<cntb:
        for i in range(n):
            if ac==k:
                break
            if a[i]:
                a[i]=0
                ac+=1
                if b[i]:
                    b[i]=0
                    bc+=1
                out+=x[i][0]
        if bc<k:
            for i in range(n):
                if bc==k:
                    break
                if b[i]:
                    b[i]=0
                    out+=x[i][0]
                    bc+=1
    else:
        for i in range(n):
            if bc==k:
                break
            if b[i]:
                b[i]=0
                bc+=1
                if a[i]:
                    a[i]=0
                    ac+=1
                out+=x[i][0]
        if ac<k:
            for i in range(n):
                if ac==k:
                    break
                if a[i]:
                    a[i]=0
                    out+=x[i][0]
                    ac+=1
    print(out)
                
        
    
else:
    print(-1)
