from itertools import accumulate
def f(a):
    return list(accumulate(sorted(a)))
def main():
    n, k = map(int, input().split())
    g10, g01, g11 = [], [], []
    for i in range(1, n + 1):
        t, a, b = map(int, input().split())
        if a == b == 1:
            g11.append(t)
        elif a == 1 and b == 0:
            g10.append(t)
        elif a == 0 and b == 1:
            g01.append(t)
    g10 = f(g10)
    g01 = f(g01)
    g11 = f(g11)
    m = min(len(g10), len(g01))
    ans = 10 ** 10
    for i, t in enumerate(g11):
        r = k - (i + 1)
        if r < 0:
            break
        if r > m:
            continue
        ans = min(ans, t + g10[r - 1] + g01[r - 1]) if r != 0 else min(ans, t)
    if ans == 10 ** 10:
        print(-1)
    else:
        print(ans)

if __name__ == '__main__':
    main()
