from collections import deque
n,k=list(map(int,input().split()))
books=[]
for i in range(0,n):
    books.append(list(map(int,input().split())))
only_a=[]
only_b=[]
intersection=[]
for i in range(0,len(books)):
    if books[i][1]==0 and books[i][2]==1:
        only_b.append(books[i])
    elif books[i][1]==1 and books[i][2]==0:
        only_a.append(books[i])
    elif books[i][1]==1 and books[i][2]==1:
        intersection.append(books[i])

only_a.sort(key=lambda x:x[0])
only_b.sort(key=lambda x: x[0])
intersection.sort(key=lambda x: x[0])
only_b=deque(only_b)
only_a=deque(only_a)
intersection=deque(intersection)
if len(intersection)+len(only_a)<k or len(intersection)+len(only_b)<k:
    print(-1)
else:
    # print(intersection)
    # print( intersection[0:k])
    total=sum([intersection[x][0] for x in range(min(k,len(intersection)))])
    if len(intersection)<k:
        total+=sum([only_a[x][0] for x in range(k-len(intersection))])

        total += sum([only_b[x][0] for x in range(k - len(intersection))])
        only_a=deque([only_a[x] for x in range(k-len(intersection))])
        only_a=deque([only_a[x] for x in range(k-len(intersection))])
    while len(intersection)>0 and len(only_a)>0 and len(only_b)>0 and (only_a[0][0]+only_b[0][0])<intersection[-1][0]:
        total=total-intersection[-1][0]+only_a[0][0]+only_b[0][0]
        only_a.popleft()
        only_b.popleft()
        intersection.pop()
    print(total)
