from bisect import bisect_right as br
from heapq import *
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    inf = 10 ** 16
    n, m, k = MI()
    tt = [[] for _ in range(4)]
    for i in range(n):
        t, a, b = MI()
        tt[a + b * 2].append((t, i + 1))

    tn = [0] * 4
    idx = [[] for _ in range(4)]
    for i in range(4):
        tn[i] = len(tt[i])
        tt[i].sort()
        idx[i] = [j for t, j in tt[i]]
        tt[i] = [t for t, j in tt[i]]
        idx[i].append(-1)
        tt[i].append(inf)

    if tn[1] + tn[3] < k or tn[2] + tn[3] < k or tn[3]<2*k-m:
        print(-1)
        exit()

    def ok(c3):
        if c3 < 2 * k - m: return False
        if c3: border = tt[3][c3 - 1]
        else: border = tt[3][0] - 1
        c0 = br(tt[0], border)
        c1 = br(tt[1], border)
        c2 = br(tt[2], border)
        if c1 + c3 < k or c2 + c3 < k: return False
        return c0 + c1 + c2 + c3 >= m

    l = -1
    r = tn[3]
    while l + 1 < r:
        c3 = (l + r) // 2
        if ok(c3): r = c3
        else: l = c3

    c = [0] * 4
    c[3] = r
    c[1] = c[2] = max(0,k - r)
    ans = idx[1][:c[1]] + idx[2][:c[2]] + idx[3][:c[3]]
    time = sum(sum(tt[i][:c[i]]) for i in range(1, 4))
    m -= c[1] + c[2] + c[3]
    hp = []
    for i in range(3):
        heappush(hp, (tt[i][c[i]], idx[i][c[i]], i))
        c[i] += 1
    for _ in range(m):
        t, j, i = heappop(hp)
        ans += [j]
        time += t
        heappush(hp, (tt[i][c[i]], idx[i][c[i]], i))
        c[i] += 1

    print(time)
    print(*ans)

main()
