def partition(list,low,high):
    p1 = low-1
    for p2 in range(low,high):
        if list[p2] < list[high]:
            p1 = p1+1
            list[p1],list[p2] = list[p2],list[p1]
    list[p1+1],list[high] = list[high],list[p1+1]
    return (p1+1)

def sort(list,low,high):
    if low < high:
        p = partition(list,low,high)
        sort(list,0,p-1)
        sort(list,p+1,high)
    return list

n = list(map(int,input().split()))
l =[]
l0 = []
l1 =[]
z = 0
for i in range(0,n[0]):
    x = list(map(int,input().split()))
    l.append(x)
for i in range (0,n[0]):
    x = l[i]
    if x[1] == 1 and x[2] == 1:
        l1.append(x[0])
    if x[1] == 0 and x[2] == 0:
        l0.append(x[0])

if len(l1) >= n[1]:
    x = []
    l1 = sort(l1,0,len(l1)-1)
    for i in range (1,n[1]):
        x.append(l1[i])
    print(sum(x))
    z =1
elif len(l1) < n[1]:
    x = n[1] - len(l1)
    if len(l0) >= x:
        l0 = sort(l0,0,len(l0)-1)
        for i in range(0,x):
            l1.append(l0[i])
        print(sum(l1))
        z = 1

if z == 0:
    print(-1)

z = [1]
print(sum(z))