n,k=[int(i) for i in raw_input().split()]
a=[[int(i) for i in raw_input().split()]for j in range(n)]
a.sort()
ca=0
cb=0
arr=[]
brr=[]
val=0
crr=[]
for i in range(n):
    if(a[i][1]==a[i][2] and a[i][1]==1):
        ca+=1
        cb+=1
        crr.append(a[i][0])
    elif(a[i][1]==a[i][2]):
        continue
    elif a[i][1]==1:
        ca+=1
        arr.append(a[i][0])
    else:
        cb+=1
        brr.append(a[i][0])
if(ca>=k and cb>=k):
    nr=[]
    for i in range(min(len(arr),len(brr))):
        nr.append(arr[i]+brr[i])
    val=0
    i=0
    j=0
    ct=0
    while i<=len(nr) and j<=len(crr) and ct<k:
        if(i==len(nr)):
            val+=crr[j]
            j+=1
        elif(j==len(crr)):
            val+=nr[i]
            i+=1
        elif(nr[i]<=crr[j]):
            val+=nr[i]
            i+=1
        else:
            val+=crr[j]
            j+=1
        ct+=1
    print val
else:
    print -1
