n, k = map(int, input().split())

books = []

for _ in range(n):
    t, a, b = map(int, input().split())
    books.append((t, a, b))

books = sorted(books, key=lambda x: x[0])

a_l = []
b_l = []
t_l = []
a_cnt = 0
b_cnt = 0

for book in books:
    if a_cnt >= k and b_cnt >= k:
        break
    else:
        if book[1] == 1 and book[2] == 0:
            if a_cnt < k:
                a_l.append(book[0])
                a_cnt += 1
        elif book[1] == 0 and book[2] == 1:
            if b_cnt < k:
                b_l.append(book[0])
                b_cnt += 1
        elif book[1] == 1 and book[2] == 1:
            if a_cnt >= k and len(a_l) != 0:
                a_l.pop()
                a_cnt = a_cnt - 1
            if b_cnt >= k and len(b_l) != 0:
                b_l.pop()
                b_cnt = b_cnt - 1

            t_l.append(book[0])
            a_cnt += 1
            b_cnt += 1

if a_cnt >= k and b_cnt >= k:
    print(sum(a_l) + sum(b_l) + sum(t_l))
else:
    print(-1)