
n, k = map(int,input().split())
listt = []
for z in range(n):
    a,b,c = map(int,input().split())
    listt.append([a,b,c])

both = []
no = []
a = []
b = []
for x in listt:
    if x[1] == 1 and x[2] == 1:
        both.append(x[0])
    elif x[1] == 1:
        a.append(x[0])
    elif x[2] == 1:
        b.append(x[0])
    else:
        no.append(x[0])

if len(both)>1:
    both.sort()
    both = both[:k]

ans = 0
a_c = 0
b_c = 0
ai = 0
bi = 0
bothi = 0
count = k

# print(a)
# print(b)
# print(both)
# print(no)

if len(a) == 0 or len(b) == 0:
    print(sum(both))
elif len(a)+len(both)<k or len(b)+len(both)<k:
    print('-1')
else:
    a.sort()
    b.sort()
    a.append(100000)
    b.append(100000)
    both.append(100000)
    flag = 0
    
    while count>0:
        if a[ai] == 100000 and b[bi] == 100000 and both[bothi] == 100000:
            flag = 1
            break
        
        if a[ai] < both[bothi] and b[bi] < both[bothi]:
            
            if a_c < k and b_c < k:
                ans += a[ai]+b[bi]
                a_c += 1
                b_c += 1
            elif a_c < k:
                ans += a[ai]
                a_c += 1
            else:
                ans += b[bi]
                b_c += 1
            count -= 1

        
        else:
            ans+= both[bothi]
            bothi += 1
            count -= 1
            a_c += 1
            b_c += 1

            
    if flag == 0:
        print(ans)
    else:
        print('-1')




    