n,k=map(int,input().split())
l=[]
def myfun(x):
    return x[0]
for i in range(n):
    m=list(map(int,input().split()))
    l.append(m)
l.sort(key=myfun)
a=0;b=0;c=0;s=0
for i in l:
    if(i[-2]==1 and i[-1]==1 and c<k):
        s+=i[0]
        c+=1
a=c;b=c
if(c<k):
    for i in l:
        if(a<k):
            if(i[-2]==1 and i[-1]!=1):
                s+=i[0]
                a+=1
        if(b<k):
            if(i[-2]!=1 and i[-1]==1):
                s+=i[0]
                b+=1
if(a!=k or b!=k):
    print("-1")
else:
    print(s)


    