import sys
input=sys.stdin.buffer.readline

n,k=[int(x) for x in input().split()]
book=[] #(ti,ai,bi)
for _ in range(n):
    book.append([int(x) for x in input().split()])
book.sort(key=lambda x:x[0]) #sort by ti asc.
t=0
a=0
b=0
aPtr=0 #move aPtr upwards until a==k, only removing books with ai==1 and bi==0
bPtr=0 #move aPtr upwards until b==k, only removing books with bi==1 and ai==0
minT=99999999999999999999999999999
for i in range(n):
    ti,ai,bi=book[i]
    if ai==1 or bi==1:
        a+=ai
        b+=bi
        t+=ti
    while aPtr<n and a>k: #remove books with ai==1 and bi==0 and increment aPtr
        if book[aPtr][1]==1 and book[aPtr][2]==0:
            a-=1
            t-=book[aPtr][0]
        aPtr+=1
    while bPtr<n and  b>k: #remove books with bi==1 and ai==0 and increment bPtr
        if book[bPtr][1]==0 and book[bPtr][2]==1:
            b-=1
            t-=book[bPtr][0]
        bPtr+=1
    if a>=k and b>=k:
        minT=min(minT,t)

if minT==99999999999999999999999999999:
    print(-1)
else:
    print(minT)