from sys import stdin, stdout
import math
from collections import defaultdict, deque

n, m, k = map(int, stdin.readline().split())
al, bl, both, hates = [], [], [], []
for i in range(n):
    t, a, b = map(int, stdin.readline().split())
    if a == 0 and b == 0:
        hates.append((t, i+1))
    elif a == 1 and b == 1:
        both.append((t, i+1))
    elif a == 1:
        al.append((t, i+1))
    elif b == 1:
        bl.append((t, i+1))

al, bl, both, hates = deque(sorted(al)[:m]), deque(sorted(bl)[:m]), deque(sorted(both)[:m]), deque(sorted(hates)[:m])
mrem, krem = m, k

res, resl = 0, []
while mrem > 0  and krem > 0:
    if mrem == krem:
        if not both:
            res = -1
            break
        t, i = both.popleft()
        res += t
        resl.append(i)
        mrem -= 1
    else:
        if al and bl:
            if both:
                tmp = float('inf')
                if hates: tmp = hates[0][0]
                if al[0][0]+bl[0][0] < both[0][0] + tmp:
                    res += al[0][0]+bl[0][0]
                    resl.append(al[0][1])
                    resl.append(bl[0][1])
                    al.popleft()
                    bl.popleft()
                    mrem -= 2
                else:
                    t, i = both.popleft()
                    res += t
                    resl.append(i)
                    t, i = hates.popleft()
                    res += t
                    resl.append(i)
                    mrem -= 2
            else:
                res += al[0][0]+bl[0][0]
                resl.append(al[0][1])
                resl.append(bl[0][1])
                al.popleft()
                bl.popleft()
                mrem -= 2
        else:
            if not both:
                res = -1
                break
            t, i = both.popleft()
            res += t
            resl.append(i)
            mrem -= 1
    krem -= 1


if krem > 0:
    print(-1)
else:
    agg = sorted(al+bl+both+hates)
    for t, i in agg[:mrem]:
        res += t
        resl.append(i)
    print(res)
    print(" ".join(map(str, resl)))
