FAST_IO = 0
if FAST_IO:
    import io, sys, atexit
    rr = iter(sys.stdin.read().splitlines()).next
    sys.stdout = _OUTPUT_BUFFER = io.BytesIO()

    @atexit.register
    def write():
        sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
    rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
rrmm = lambda n: [rrm() for _ in xrange(n)]

####


def solve(N, M, K, A):
    alice = []
    bob = []
    shared = []
    neither = []
    for i, (t, a, b) in enumerate(A, 1):
        if a and b:
            shared.append([t, i])
        elif a:
            alice.append([t, i])
        elif b:
            bob.append([t, i])
        else:
            neither.append([t, i])
    shared.sort()
    alice.sort()
    bob.sort()
    neither.sort()

    Palice = [0]
    Pbob = [0]
    Pneither = [0]
    for x, i in alice:
        Palice.append(Palice[-1] + x)
    for x, i in bob:
        Pbob.append(Pbob[-1] + x)
    for x, i in neither:
        Pneither.append(Pneither[-1] + x)

    ans = INF = float('inf')
    ansix = None
    s = 0
    # TODO: no shared books
    for i, (x, _index) in enumerate(shared, 1):
        s += x
        # shared i books
        rem = K - i
        if rem < 0: continue
        total_read = rem + rem + i
        if total_read > M: continue

        asu = Palice[rem] if rem < len(Palice) else INF
        bsu = Pbob[rem] if rem < len(Pbob) else INF

        rem2 = M - total_read
        nsu = Pneither[rem2] if rem2 < len(Pneither) else INF
        cand = s + asu + bsu + nsu
        if cand < ans:
            ans = cand
            ansix = i, rem, rem2

    rem = K
    total_read = rem + rem + 0
    if total_read <= M:
        asu = Palice[rem] if rem < len(Palice) else INF
        bsu = Pbob[rem] if rem < len(Pbob) else INF
        rem2 = M - total_read
        nsu = Pneither[rem2] if rem2 < len(Pneither) else INF
        cand = asu + bsu + nsu
        if cand < ans:
            ans = cand
            ansix = 0, rem, rem2
    if ans == INF: return None
    report = []
    # shared
    for i in xrange(ansix[0]):
        report.append(shared[i][1])
    for i in xrange(ansix[1]):
        report.append(alice[i][1])
        report.append(bob[i][1])
    for i in xrange(ansix[2]):
        report.append(neither[i][1])

    return ans, report


N, M, K = rrm()
A = rrmm(N)
ans = solve(N, M, K, A)
if ans is None:
    print -1
else:
    print ans[0]
    report = ans[1]
    print " ".join(map(str, report))