input=__import__('sys').stdin.readline
n,k=map(int,input().split())
s=[]
alisa=bob=0
for i in range(n):
    t,a,b=map(int,input().split())
    if a and b:s.append([t,a,b])
    elif b:s.append([t,2,3])
    elif a:s.append([t,3,2])
    alisa+=a;bob+=b
if alisa<k or bob<k:print(-1)
else:
    s.sort()
    alisa=bob=0
    ans=0
    i=0
    at=[]
    bt=[]
    while alisa<k or bob<k:
        t,a,b=s[i]
        if a==1 and b==1:ans+=t;alisa+=1;bob+=1
        elif a==3 and alisa<k:ans+=t;alisa+=1;at.append(t)
        elif b==3 and bob<k:ans+=t;bob+=1;bt.append(t)
        i+=1
    i=len(at)-1
    while i>=0 and alisa>k:
        ans-=at[i]
        i-=1
        alisa-=1
    i=len(bt)-1
    while i>=0 and bob>k:
        ans-=bt[i]
        i-=1
        bob-=1
    print(ans)