n, k = input().split()
n, k = int(n), int(k)

ca, cb = 0, 0
t, a, b = [], [], []
for i in range(n):
    ti, ai, bi = input().split()
    t.append(int(ti))
    a.append(int(ai))
    b.append(int(bi))
    ca += int(ai)
    cb += int(bi)

if ca < k or cb < k:
    print(-1)
    exit(0)


abt, at, bt = [], [], []
for i in range(n):
    if a[i] == 1:
        if b[i] == 1:
            abt.append(t[i])
        else:
            at.append(t[i])
    elif b[i] == 1:
        bt.append(t[i])

at.sort() #tried merge_sort but pythons implementation is the fastest. (of course)
bt.sort()
abt.sort()
at = [10**4 + 1] + at[::-1]
bt = [10**4 + 1] + bt[::-1]
abt = [2 * 10**4 + 2] + abt[::-1]
ca, cb = 0, 0
t = 0

while ca < k and cb < k:
    if at[-1] + bt[-1] >= abt[-1]:
        t += abt.pop()
        ca, cb = ca + 1, cb + 1
    elif at[-1] >= bt[-1]:
        t += bt.pop()
        cb += 1
    else:
        t += at.pop()
        ca += 1

if ca >= k and cb >= k:
    pass

elif ca >= k:
    while cb < k:
        if abt[-1] >= bt[-1]:
            t += bt.pop()
        else:
            t += abt.pop()
        cb += 1

elif cb >= k:
    while ca < k:
        if abt[-1] >= at[-1]:
            t += at.pop()
        else:
            t += abt.pop()
        ca += 1

print(t)