import math

N, K = [int(i) for i in input().split()]
T, A, B = [], [], []

for i in range(N):
    t, a, b = [int(j) for j in input().split()]
    T.append(t)
    A.append(a)
    B.append(b)

S = []
for i in range(N):
    if A[i] == 0 and B[i] == 0:
        S.append(math.inf)
    elif A[i] == 0 or B[i] == 0:
        S.append(T[i])
    else:
        S.append(T[i]/2)

sorted_book_ids = [i[1] for i in sorted([(s, i) for i, s in enumerate(S)])]
ak = 0
bk = 0
i = 0
ans = 0
els = []
while ak < K or bk < K:
    if i >= len(sorted_book_ids):
        ans = -1
        break
    if A[sorted_book_ids[i]]:
        ak += 1
    if B[sorted_book_ids[i]]:
        bk += 1
    # print('use ', sorted_book_ids[i], T[sorted_book_ids[i]])
    ans += T[sorted_book_ids[i]]
    els.append(sorted_book_ids[i])
    i += 1

if ans == -1:
    print(ans)
else:
    for el in els[::-1]:
        if ak == K:
            break
        if A[el] and not B[el]:
            ans -= T[el]
            ak -= 1

    for el in els[::-1]:
        if bk == K:
            break
        if B[el] and not A[el]:
            ans -= T[el]
            bk -= 1
    print(ans)
