n,k=map(int,input().split())
ans=0;tb=[];count=0;ta=[];non=[]
for i in range(n):
    t,a,b=map(int,input().split())
    if(a+b==2):
        ans+=t
        count+=1
    elif a==1:
        ta.append(t)
    elif b==1:
        tb.append(t)

x=k-count
if(len(ta)<x or len(tb)<x):
    print(-1)
else:
    ans+=sum(sorted(ta)[:x]+sorted(tb)[:x])
    print(ans)

