n, k = map(int, input().split())
books = []
for _ in range(n):
    book = tuple(map(int, input().split()))
    if book[1] == book[2] == 0:
        continue;
    books.append(book)
books.sort(key=lambda b:b[0])
books.sort(key=lambda b:b[1]+b[2], reverse=True)

alice_cnt = bob_cnt = k
ans = 0
for book in books:
    if alice_cnt + bob_cnt == 0:
        break

    if book[1] + book[2] == 2:
        alice_cnt -= 1
        bob_cnt -= 1
        ans += book[0]
    elif book[1] == 1:
        alice_cnt -= 1
        ans += book[0]
    else:
        bob_cnt -= 1
        ans += book[0]
print(ans if alice_cnt + bob_cnt == 0 else -1)