import sys
import math
import collections
import heapq

def set_debug(debug_mode=False):
    if debug_mode:
        fin = open('input.txt', 'r')
        sys.stdin = fin


def int_input():
    return list(map(int, input().split()))


if __name__ == '__main__':
    # set_debug(True)

    # t = int(input())
    t = 1

    for ti in range(1, t + 1):
        n, k = int_input()
        both = []
        single = []
        A = 0
        B = 0

        for _ in range(n):
            t, a, b = int_input()
            if a == 1 and b == 1:
                A += 1
                B += 1
                both.append(t)
            elif a == 1:
                A += 1
                single.append((t, 1))
            elif b == 1:
                B += 1
                single.append((t, -1))

        if A < k or B < k:
            print(-1)
            continue

        if len(both) >= k:
            both.sort()
            print(sum(both[:k]))
        else:
            A = len(both)
            B = len(both)

            res = sum(both)

            heapq.heapify(single)

            while single:
                if A == k and B == k:
                    break
                else:
                    t, belong = heapq.heappop(single)
                    if belong == 1:
                        if A < k:
                            A += 1
                            res += t
                    elif belong == -1:
                        if B < k:
                            B += 1
                            res += t

            print(res)

