def process(a, b, k):
    # a is constraining and should be processed first
    result = 0
    bIndices = {i for _, i in b}
    used = set()
    aNeeded, bNeeded = k, k
    for val, i in a:
        if aNeeded == 0:
            break
        if i in bIndices:
            bNeeded -= 1
        aNeeded -= 1
        used.add(i)
        result += val
    for val, i in b:
        if bNeeded == 0:
            break
        if i in used:
            continue
        result += val
        bNeeded -= 1
    return result


n, k = map(int, input().split())
aVals, bVals = [], []
countA, countB = 0, 0
for i in range(n):
    t, a, b = map(int, input().split())
    countA += a
    countB += b
    if a:
        aVals.append((t, i))
    if b:
        bVals.append((t, i))
if countA < k or countB < k:
    print(-1)
else:
    aVals.sort()
    bVals.sort()
    if countA <= countB:
        print(process(aVals, bVals, k))
    else:
        print(process(bVals, aVals, k)) 