from sys import stdin, stdout

n, k = map(int, stdin.readline().split())
alice = []
bob = []
together = []
for _ in range(n):
    t, a, b = map(int, stdin.readline().split())
    if a and b:
        together += t,
    elif a:
        alice += t,
    else:
        bob += t,
sa, sb, st = len(alice), len(bob), len(together)
if sa + st < k or sb + st < k:
    stdout.write('-1')
    exit()
alice.sort()
bob.sort()
together.sort()
time = 0
for _ in range(k):
    if sa and sb and st:
        if together[0] < alice[0] + bob[0]:
            time += together[0]
            together = together[1:]
            st -= 1
        else:
            time += alice[0] + bob[0]
            alice = alice[1:]
            bob = bob[1:]
            sa -= 1
            sb -= 1
    elif st:
        time += together[0]
        together = together[1:]
        st -= 1
    else:
        time += alice[0] + bob[0]
        alice = alice[1:]
        bob = bob[1:]
        sa -= 1
        sb -= 1
stdout.write(str(time))