def solve():
    n, k = list(map(int, input().split()))
    a = []
    b = []
    both = []
    alice = 0
    bob = 0
    coincidence = 0

    for i in range(n):
        t, a_, b_ = list(map(int, input().split()))
        if b_ and a_:
            both.append(t)
            coincidence += 1
        elif a_ == 1:
            a.append(t)
            alice += 1
        elif b_ == 1:
            b.append(t)
            bob += 1

    if alice+coincidence < k or bob+coincidence<k:
        print(-1)
    else:
        both.sort()
        a.sort()
        b.sort()

        out = 0
        while k>0:
            if len(a) == 0 or len(b) == 0:
                out += sum(both[:k])
                k = 1
            elif len(both) > 0:
                minimun = a[0] + b[0]
                aux = [val for val in both if val > minimun]
                
                if 0 < len(aux):
                    out += sum(aux)
                    del both[:len(aux)]
                else:
                    out += minimun
                    a.pop(0)
                    b.pop(0)
            else:
                out += sum(a[:k]) + sum(b[:k])
                k = 1
            k -= 1

        print(out)


cases = 1
for test in range(cases):
    solve()
