n,k=map(int,input().split())
L1=[]
L2=[]
L3=[]
s=0
for i in range(n):
   t,a,b=map(int,input().split())
   if a==1 and b==1:
      L1.append(t)
   elif a==1 and b==0:
      L2.append(t)
   elif a==0 and b==1:
      L3.append(t)
L1.sort()
L2.sort()
L3.sort()
if k==len(L1):
   print(sum(L1))
elif k<len(L1):
   print(sum(L1[:k+1]))
else:
   s=s+sum(L1)
   k=k-len(L1)
   if k<=len(L2) and k<=len(L3):
      s=s+sum(L2[:k+1])+sum(L3[:k+1])
      print(s)
   else:
      print(-1)