# https://codeforces.com/contest/1374/problem/E1

def min_time(tot_books, books_like, read_time, a_time, b_time):
    time = []
    temp_a = []
    temp_b = []
    if min(sum(a_time), sum(b_time)) >= books_like:
        for x in range(tot_books):
            if a_time[x] == b_time[x] == 1:
                time.append(read_time[x])
            elif a_time[x] == 0 and b_time[x] == 1:
                temp_b.append(read_time[x])
            elif a_time[x] == 1 and b_time[x] == 0:
                temp_a.append(read_time[x])
        if len(time) > books_like:
            time.sort(reverse=True)
            time = time[len(time) - books_like:]
            temp_a.sort(), temp_b.sort()
        y = 0
        while y != (min(len(temp_a), len(temp_b))):
            # print(min(len(temp_a), len(temp_b)))
            # print(y)
            # print(time, temp_a, temp_b)
            if len(time) != books_like:
                time.append(temp_a[y] + temp_b[y])
                del (temp_a[y], temp_b[y])
                y -= 1
                if len(time) == books_like:
                    y = -1
            elif temp_a[y] + temp_b[y] < time[y]:
                time[y] = temp_a[y] + temp_b[y]
            else:
                break
            y += 1
        # print(time, temp_a, temp_b)
        return sum(time)
    else:
        return -1


n, k = map(int, input().split())
t = []
a = []
b = []
for i in range(n):
    x, y, z = map(int, input().split())
    t.append(x), a.append(y), b.append(z)
print(min_time(n, k, t, a, b))
