from sys import stdin

def readline():
    return stdin.readline()

#tests = int(readline())

def solve(n, k, a):
    a.sort()
    al = 0
    b = 0
    res = []
    resA = []
    resB = []
    for i in range(0, n):
        al += a[i][1]
        b += a[i][2]
        if a[i][1] == 1 and a[i][2] == 1:
            res.append(i)
        elif a[i][1] == 1:
            resA.append(i)
        elif a[i][2] == 1:
            resB.append(i)

        if al == k and b == k:
            break

    if al < k or b < k:
        return -1

    if len(res) < k:
        res += resA[0:(k - len(res) // 2)] + resB[0:(k - len(res) // 2)]

    time = 0
    for i in range(0, len(res)):
        time += a[res[i]][0]
    return time


#for t in range(0, tests):
#n = int(readline().rstrip("\n"))
#s = readline().rstrip("\n")
n, k = list(map(int, readline().rstrip("\n").split(' ')))
a = []
for i in range(0, n):
    a.append(list(map(int, readline().rstrip("\n").split(' '))))

print(solve(n, k, a))
