n,k=(map(int,input().split()))
a=[]
b=[]
c=[]
for i in range(n):
    t,a1,b1=(map(int,input().split()))
    if a1==1 and b1==0:
        a.append(t)
    if b1==1 and a1==0:
        b.append(t)
    if a1==1 and b1==1:
        c.append(t)
a.sort()
b.sort()
c.sort()
if len(a)+len(c)<k or len(b)+len(c)<k:
    print(-1)
else:
    ak=0
    bk=0
    i=0
    j=0
    ans=0
    while ak<k:
        if i<len(a) and j<len(c):
            if a[i]<c[j]:
                ans+=a[i]
                ak+=1
            else:
                ans+=c[j]
                j+=1
                ak+=1
                bk+=1
        else:
            if i<len(a):
                ans+=a[i]
                ak+=1
                i+=1
            if j<len(c):
                ans+=c[j]
                j+=1
                ak+=1
                bk+=1
    
    i=0
    while bk<k:
        if i<len(b) and j<len(c):
            if b[i]<c[j]:
                ans+=b[i]
                bk+=1
            else:
                ans+=c[j]
                j+=1
                ak+=1
                bk+=1
        else:
            if i<len(b):
                ans+=b[i]
                bk+=1
                i+=1
            if j<len(c):
                ans+=c[j]
                j+=1
                bk+=1
                ak+=1
    print(ans)
        
            
            

            
    
    
    