from heapq import *
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n,k=MI()
    at=[]
    bt=[]
    ca=cb=0
    tab=LLI(n)
    tab.sort(key=lambda x:(x[0],-x[1]-x[2]))
    ans=0
    mn=10**16
    for t,a,b in tab:
        if a and b:
            ans+=t
            ca+=1
            cb+=1
            if ca>k:
                t=-heappop(at)
                ca-=1
                ans-=t
            if cb > k:
                t = -heappop(bt)
                cb -= 1
                ans -= t
        elif a and ca<k:
            ans+=t
            ca+=1
            heappush(at,-t)
        elif b and cb<k:
            ans+=t
            cb+=1
            heappush(bt,-t)
        #print(a,b,ca,cb,ans)
        if ca==k and cb==k:
            mn=min(ans,mn)
            if not at and not bt:break
    if ca==k and cb==k:print(mn)
    else:print(-1)

main()