l=[]
n,k=str(input()).split(" ")
n=int(n)
k=int(k)
a1=[]
a2=[]
c1=0
c2=0
su=0
comm=0
for j in range(n):
    t,a,b=str(input()).split(" ")
    t=int(t)
    a=int(a)
    b=int(b)
    if(a==1 and b==1):
        c1+=1
        c2+=1
        comm+=1
        su=t
        continue
    if(a==1):
        c1+=1
        a1.append(t)
    if(b==1):
        c2+=1
        a2.append(t)
a1.sort()
a2.sort()
if(c1<k-comm and c2<k-comm):
    print(-1)
else:
    for j in range(k-comm):
        su=su+a1[0]+a2[0]
    print(su)    
    

        