FAST_IO = 1
if FAST_IO:
    import io, sys, atexit
    rr = iter(sys.stdin.read().splitlines()).next
    sys.stdout = _OUTPUT_BUFFER = io.BytesIO()

    @atexit.register
    def write():
        sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
    rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
rrmm = lambda n: [rrm() for _ in xrange(n)]

####


def solve(N, K, A):
    alice = []
    bob = []
    shared = []
    for t, a, b in A:
        if a and b:
            shared.append(t)
        elif a:
            alice.append(t)
        elif b:
            bob.append(t)
    shared.sort()
    alice.sort()
    bob.sort()

    Palice = [0]
    Pbob = [0]
    for x in alice:
        Palice.append(Palice[-1] + x)
    for x in bob:
        Pbob.append(Pbob[-1] + x)

    ans = INF = float('inf')
    s = 0
    # TODO: no shared books
    for i, x in enumerate(shared, 1):
        s += x
        # shared i books
        rem = K - i
        if rem < 0: continue
        asu = Palice[rem] if rem < len(Palice) else INF
        bsu = Pbob[rem] if rem < len(Pbob) else INF
        cand = s + asu + bsu
        if cand < ans: ans = cand
    rem = K
    asu = Palice[rem] if rem < len(Palice) else INF
    bsu = Pbob[rem] if rem < len(Pbob) else INF
    cand = asu + bsu
    if cand < ans: ans = cand
    if ans == INF: return -1
    return ans


N, K = rrm()
A = rrmm(N)
print solve(N, K, A)