from functools import cmp_to_key
n, k = map(int, input().split())
a = []
b = []


def comparator(subInfo1, subInfo2):
    if subInfo1[0] > subInfo2[0]:
        return 1
    elif subInfo1[0] == subInfo2[0]:
        if subInfo1[2] > subInfo2[2]:
            return -1
        return 1

    return -1


for i in range(n):
    f = list(map(int, input().split()))
    if f[1] == 1:
        a.append(f)
    elif f[2] == 1:
        b.append(f)
a = sorted(a, key=cmp_to_key(comparator))
b.sort()
ans = 0
a1, b1 = 0, 0
b2 = 0
h = -1
q = [0] * k
for i in range(len(a)):
    if a[i][2] == 1:
        b1 += 1
        q[b2] = a[i][0] + q[b2 - 1]
        b2 += 1
    a1 += 1
    ans += a[i][0]
    if a1 == k:
        h = i
        break
h += 1
while h < len(a) and b2 < k:
    if a[h][2] == 1:
        q[b2] = a[h][0]
        b2 += 1
    h += 1
    if b2 == k:
        break
i = 0
while i < len(b) and b1 < k:
    if q[b1] == 0:
        q[b1] = b[i][0]
        i += 1
    else:
        if q[b1] > b[i][0]:
            q[b1] = b[i][0]
            i += 1
    ans += q[b1]
    b1 += 1
if a1 == b1 == k:
    print(ans)
else:
    print(-1)
