n, k = map(int, raw_input().split())


both = []
alice = []
bob = []

for _ in xrange(n):
    t, a, b = map(int, raw_input().split())
    if a == 1 and b == 1:
        both.append(t)
    elif a == 1 and b == 0:
        alice.append(t)
    elif a == 0 and b == 1:
        bob.append(t)
    
import heapq

heapq.heapify(both)
heapq.heapify(alice)
heapq.heapify(bob)

ak = 0 
bk = 0
t = 0
done = False

# print both
# print alice
# print bob

if len(both) + len(alice) < k or len(both) + len(bob) < k:
    print -1
    done = True
    ak = k
    bk =k

while ak < k or bk < k:
    if len(both) == 0:
        if ak < k:
            t += heapq.heappop(alice)
            ak += 1
            continue
        if bk < k:
            t += heapq.heappop(bob)
            bk += 1
            continue
    elif len(alice) == 0:
        if ak < k:
            t += heapq.heappop(both)
            ak += 1
            bk += 1
            continue
        if bk < k:
            if both[0] <= bob[0]:
                t += heapq.heappop(both)
                ak += 1
                bk += 1
                continue
            else:
                t += heapq.heappop(bob)
                bk += 1
                continue
    elif len(bob) == 0:
        if bk < k:
            t += heapq.heappop(both)
            ak += 1
            bk += 1
            continue
        if ak < k:
            if both[0] <= alice[0]:
                t += heapq.heappop(both)
                ak += 1
                bk += 1
                continue
            else:
                t += heapq.heappop(alice)
                ak += 1
                continue
    else:
        if ak < k and bk < k:
            if both[0] <= alice[0] + bob[0]:
                t += heapq.heappop(both)
                ak += 1
                bk += 1
                continue
            else:
                t += heapq.heappop(alice)
                t += heapq.heappop(bob)
                ak += 1
                bk += 1
                continue
        elif bk < k:
            if both[0] <= bob[0]:
                t += heapq.heappop(both)
                bk += 1
                ak += 1
                continue
            else:
                t += heapq.heappop(bob)
                bk += 1
                continue
        elif ak < k:
            if both[0] <= alice[0]:
                t += heapq.heappop(both)
                ak += 1
                bk += 1
                continue
            else:
                t += heapq.heappop(alice)
                ak += 1
                continue

if not done:
    print t