import collections
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())



import heapq
n, k = rrm()
both = []
A = []
B = []
for _ in range(n):
    l, a,b = rrm()
    if a==b==1:
        heapq.heappush(both, l)
    elif a == 1:
        heapq.heappush(A, l)
    elif b == 1:
        heapq.heappush(B,l)
ans = 0
seen = False
while k:
    if both and A and B:
        if both[0]<(A[0]+B[0]):
            ans += heapq.heappop(both)
        else:
            ans+= heapq.heappop(A)
            ans+= heapq.heappop(B)
    elif both:
        ans+= heapq.heappop(both)
    elif A and B:
        ans+= heapq.heappop(A)
        ans+=heapq.heappop(B)
    else:
        seen = True
        print -1
        
    k-=1
if not seen:
    print(ans)
    