n, k = map(int, input().split())
a = []
for i in range(n):
    x,y,z = map(int, input().split())
    a.append([x,y,z])
a.sort()
alice_count = 0
bob_count = 0
ans = 0
alice = []
bob = []
combine = []
for i in range(n):
    if a[i][1] == 1 and a[i][2] == 1:
        ans += a[i][0]
        alice_count += 1
        bob_count += 1
        combine.append(a[i][0])
    elif a[i][1] == 1:
        ans += a[i][0]
        alice.append(a[i][0])
        alice_count += 1
    elif a[i][2] == 1:
        ans += a[i][0]
        bob.append(a[i][0])
        bob_count += 1
    if alice_count >= k and bob_count >= k:
        break
if alice_count < k or bob_count < k:
    print('-1')
else:
    alice.sort(reverse = True)
    bob.sort(reverse = True)
    i = 0
    while(bob_count > alice_count and i<len(bob)):
        ans -= bob[i]
        bob_count -= 1
        i += 1
    i = 0 
    while(alice_count > bob_count and i < len(alice)):
        ans -= alice[i]
        alice_count -= 1
        i += 1
    print(ans)
        
        