n, k = [int(ele) for ele in input().split()]
books = []
for i in range(n):
    books.append([int(ele) for ele in input().split()])

books.sort(key = lambda x: x[0])

A, B, costA, costB = [], [], [], []
countA, countB = 0, 0
tt = 0

i = 0
while(countA < k and countB < k and i<n):
    book = books[i]
    if book[1] == 1 and book[2] == 1:
        countA += 1 
        countB += 1 
        A.append(i)
        B.append(i)
        tt += book[0]
    elif book[1] == 1:
        countA += 1
        A.append(i)
        tt += book[0]
        costA.append(book[0])
    elif book[2] == 1:
        countB += 1
        B.append(i)
        tt += book[0]
        costB.append(book[0])
    i += 1


while countA < k and i<n:
    book = books[i]
    if book[1] == 1:
        countA += 1
        A.append(i)
        tt += book[0]
        if book[2] == 1:
            countB += 1 
            B.append(i)
    i += 1
    
while countB < k and i<n:
    book = books[i]
    if book[2] == 1:
        countB += 1
        B.append(i)
        tt += book[0]
        if book[1] == 1:
            countA += 1 
            A.append(i)
    i += 1

#print(countA, countB)
if i == n and (countA < k or countB < k):
    print(-1)
else:
    if countA == countB:
        print(tt)
    elif countA > countB:
        while(countA != countB):
            tt -= costA[-1]
            del costA[-1]
            countA -= 1 
        print(tt)
    else:
        while(countA != countB):
            tt -= costB[-1]
            del costB[-1]
            countB -= 1 
        print(tt)