import sys
if sys.subversion[0] == "PyPy":
    import io, atexit
    sys.stdout = io.BytesIO()
    atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
    
    sys.stdin = io.BytesIO(sys.stdin.read())
    input = lambda: sys.stdin.readline().rstrip()

RS = raw_input
RI = lambda x=int: map(x,RS().split())
RN = lambda x=int: x(RS())
''' ...................................................................... '''

n,k = RI()
alice,bob,com = [],[],[]

for i in xrange(n):
    t,a,b = RI()
    if a==b and a==1:
        com.append(t)
    elif a==1:
        alice.append(t)
    elif b==1:
        bob.append(t)

alice.sort(); bob.sort(); com.sort()
n1,n2,n3 = len(alice),len(bob),len(com)

if n1+n3 < k or n2+n3<k:
    print -1
else:
    ans = 0
    i,j,l = 0,0,0
    left1,left2 = k,k

    while l<n3 and (left1>n1 or left2>n2):
        ans += com[l]
        left1-=1
        left2-=1
        l+=1

    while left1>0 and left2>0:
        if l<n3 and (i>=n1 or j>=n2 or com[l]<=(alice[i]+bob[j])):
            ans += com[l]
            l+=1
            left1-=1
            left2-=1
        else:
            ans += alice[i]
            i+=1; left1-=1

            ans += bob[j]
            j+=1; left2-=1
        

    while left1>0:
        ans += alice[i]
        i+=1
        left1-=1
    while left2>0:
        ans += bob[j]
        j+=1
        left2-=1
        
    print ans
    

    
