
n, k = map(int, input().split())
d_a = set()
d_b = set()
for _ in range(n):
    t, a, b = map(int, input().split())
    if a == 1:
        d_a.add(t)
    if b == 1:
        d_b.add(t)
if len(d_a) < k or len(d_b) < k:
    print(-1)
else:
    l_a = list(d_a)[:k]
    l_b = list(d_b)[:k]
    u = d_a & d_b
    if len(u) > k:
        print(sum(list(sorted(list(u)))[:k]))
    else:
        l_a = list(sorted(list(d_a - u)))[:k-len(u)]
        l_b = list(sorted(list(d_b - u)))[:k-len(u)]
        print(sum(l_a)+sum(l_b)+sum(u))
