n,k=(map(int,input().split()))
a=[]
b=[]
for i in range(n):
    t,a1,b1=(map(int,input().split()))
    if a1==1:
        a.append(t)
    if b1==1:
        b.append(t)
a.sort()
b.sort()
if len(a)<k or len(b)<k:
    print(-1)
else:
    ans1=0
    ans2=0
    for i in range(k):
        ans1+=a[i]
        ans2+=b[i]
    print(max(ans1,ans2))
    
            
    
    
    