import io
import os

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline


class Books:
    def __init__(self, time, alice_like, bob_like):
        self.time = time
        self.alice_like = alice_like
        self.bob_like = bob_like


def solve():
    n, k = map(int, input().split())
    books = []

    for i in range(n):
        t, a, b = map(int, input().split())
        books.append(Books(t, a == 1, b == 1))

    books_everybody_like = []
    books_alice_like = []
    books_bob_like = []
    for b in books:
        if b.alice_like and b.bob_like:
            books_everybody_like.append(b)
        elif b.alice_like:
            books_alice_like.append(b)
        elif b.bob_like:
            books_bob_like.append(b)

    books_alice_like = sorted(books_alice_like, key=lambda x: x.time)
    books_bob_like = sorted(books_bob_like, key=lambda x: x.time)

    for a, b in zip(books_alice_like, books_bob_like):
        books_everybody_like.append(Books(a.time + b.time, True, True))

    if len(books_everybody_like) < k:
        print(-1)
        return

    books_everybody_like = sorted(books_everybody_like, key=lambda x: x.time)

    answer = 0
    for i in range(k):
        answer += books_everybody_like[i].time

    print(answer)


if __name__ == '__main__':
    solve()
