[n, k] = list(map(int, input().split(' ')))

alice_books = []
bob_books = []
common_books = []
# all_books = []
for _ in range(n):
    [t, a, b] = list(map(int, input().split(' ')))
    if a == 1 and b == 0:
        alice_books.append(t)
    elif b == 1 and a == 0:
        bob_books.append(t)
    elif a == 1 and b == 1:
        common_books.append(t)

alice_books = list(sorted(alice_books))
bob_books = list(sorted(bob_books))
common_books = list(sorted(common_books))

if len(alice_books) + len(common_books) < k:
    print(-1)
elif len(bob_books) + len(common_books) < k:
    print(-1)
else:
    cur_alice = 0
    cur_bob = 0
    cur_common = 0
    total_time = 0
    alice_req = k
    bob_req = k

    while alice_req > 0 and bob_req > 0:
        alice_time = alice_books[cur_alice] if cur_alice < len(alice_books) else None
        bob_time = bob_books[cur_bob] if cur_bob < len(bob_books) else None
        common_time = common_books[cur_common] if cur_common < len(common_books) else None

        # print(cur_alice, cur_bob, cur_common)
        if not common_time:
            if alice_req > 0:
                alice_req -= 1
                total_time += alice_time
                cur_alice += 1
            elif bob_req > 0:
                bob_req -= 1
                total_time += bob_time
                cur_bob += 1
        else:
            if alice_req > 0:
                if alice_time and alice_time + (bob_time or 0) < common_time:
                    alice_req -= 1
                    total_time += alice_time
                    cur_alice += 1
                else:
                    alice_req -= 1
                    bob_req -= 1
                    cur_common += 1
                    total_time += common_time
            elif bob_req > 0:
                if bob_time and bob_time + (alice_time or 0) < common_time:
                    bob_req -= 1
                    total_time += bob_time
                    cur_bob += 1
                else:
                    alice_req -= 1
                    bob_req -= 1
                    cur_common += 1
                    total_time += common_time

    print(total_time)
