from sys import stdin
import math
A = list(map(int,stdin.readline().split()))
n = A[0]
k = A[1]
oneone=list()
onezero=list()
zeroone=list()

for t in range(0,n):
    B = list(map(int,stdin.readline().split()))
    if B[1]==1 and B[2]==1:
        oneone.append(B[0])
    elif B[1]==1 and B[2]==0:
        onezero.append(B[0])
    elif B[1]==0 and B[2]==1:
        zeroone.append(B[0])

oneone.sort()
zeroone.sort()
onezero.sort()
ans=0


if len(oneone)+min(len(onezero),len(zeroone))<k:
    print(-1)
    Q=1
else:
    while k>0:
           if len(oneone)>0:
                  AA=oneone[0]
                  oneone.remove(oneone[0])
           else:
                  AA=10**5

           if min(len(onezero),len(zeroone))>0:
                  BB=onezero[0]+zeroone[0]
                  onezero.remove(onezero[0])
                  zeroone.remove(zeroone[0])
           else:
                  BB=10**5

           ans+=min(AA,BB)
           k-=1

print(ans)