from __future__ import print_function, division
from sys import stdin, stdout

rstr = lambda: stdin.readline().strip()
rstrs = lambda: [str(x) for x in stdin.readline().split()]
rint = lambda: int(stdin.readline())
rints = lambda: [int(x) for x in stdin.readline().split()]
arr_2d = lambda n: [rints() for i in range(n)]
out = []

n, k = rints()
a = sorted([rints() for _ in range(n)], key=lambda x: x[0])
alice, bob, o_o, o_z, z_o, ans = 0, 0, [], [], [], 0

for i in range(n):
    if alice >= k and bob >= k:
        if a[i][1] == a[i][2] == 1:
            o_o.append(a[i][0])

        continue

    if a[i][1] and a[i][2]:
        ans += a[i][0]
        alice += 1
        bob += 1

    elif a[i][1] and alice < k:
        alice += 1
        ans += a[i][0]
        o_z.append(a[i][0])

    elif a[i][2] and bob < k:
        bob += 1
        ans += a[i][0]
        z_o.append(a[i][0])

if alice < k or bob < k:
    print(-1)
else:
    if len(o_z) > len(z_o):
        for i in range(len(o_z) - len(z_o)):
            ans -= o_z.pop()

    if len(z_o) > len(o_z):
        for i in range(len(z_o) - len(o_z)):
            ans -= z_o.pop()

    o_o.reverse()

    while o_z and z_o and o_o:
        if o_z[-1] + z_o[-1] <= o_o[-1]:
            break

        ans -= o_z.pop() + z_o.pop()
        ans += o_o.pop()

    print(ans)
