n,k=map(int,input().split())
t=[]
a=[]
b=[]
for _ in range(n):
     t1,a1,b1=map(int,input().split())
     if a1==1 and b1==1:
         t.append(t1)
     elif a1==1 and b1==0:
         a.append(t1)
     else:
         b.append(t1)
a.sort()
b.sort()
k1=min(len(a),len(b))
for i in range(k1):
    t.append(a[i]+b[i])
if len(t)<k:
    print("-1")
elif k==1:
    print(t[0])
else:
    print(sum(t[:k]))