# Secdra @2020
from functools import cmp_to_key


class Node:
    def __init__(self, t, a, b):
        self.t = t
        self.a = a
        self.b = b

    def __lt__(self, other):
        if (self.a + self.b) == (other.a + other.b):
            return self.t > other.t
        else:
            return (self.a + self.b) > (other.a + other.b)
        # if self.t == other.t:
        #     return (self.a + self.b) > (other.a + other.b)
        # return self.t < other.t


def main():
    n, k = map(int, input().split())
    data = list()
    for _ in range(n):
        t, a, b = map(int, input().split())
        if a != 0 or b != 0:
            book = Node(t, a, b)
            data.append(book)

    data.sort()
    ans = 0
    done_a = 0
    done_b = 0
    for book in data:
        if (done_a >= k and book.b != 1) or (done_b >= k and book.a != 1):
            continue
        ans += book.t
        done_a += book.a
        done_b += book.b
        if done_a >= k and done_b >= k:
            print(ans)
            return
    print(-1)


if __name__ == '__main__':
    main()
