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
for i in range(n):
    if(a[i][1]==a[i][2] and a[i][1]==1):
        ca+=1
        cb+=1
        val+=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])
    while(ca>k):
        arr.pop()
        ca-=1
    while(cb>k):
        brr.pop()
        cb-=1
    if(ca==k and cb==k):
        break
if(ca==k and cb==k):
    for i in arr:
        val+=i
    for i in brr:
        val+=i
    print val
else:
    print -1
