#!/usr/bin/env python3
import io
import os

input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def get_str():
    return input().decode().strip()

def rint():
    return map(int, input().split())

def oint():
    return int(input())

n, m, k = rint()
tab = []
for i in range(n):
    t1, t2, t3 = rint()
    tab.append((t1, t2, t3, i+1))
tab.sort(key=lambda i: (i[0], -(i[1] + i[2])))
ai = []
bi = []
read = [0]*n
tot_time = 0
ka = 0
kb = 0
for i in range(n):
    t, a, b, tabi = tab[i]
    if a and not b:
        if ka < k:
            ka += 1
            ai.append(i)
            tot_time += t
            read[i] = 1
    elif b and not a:
        if kb < k:
            kb += 1
            bi.append(i)
            tot_time += t
            read[i] = 1
    elif a and b:
        if ka < k or kb < k:
            ka += 1
            kb += 1
            tot_time += t
            read[i] = 1
            if ka > k:
                if len(ai):
                    read[ai[-1]] = 0
                    ta = tab[ai.pop()][0]
                    tot_time -= ta
                    ka -= 1
            if kb > k:
                if len(bi):
                    read[bi[-1]] = 0
                    tb = tab[bi.pop()][0]
                    tot_time -= tb
                    kb -= 1
        elif ka >= k and kb >= k:
            if len(ai):
                ia = ai[-1]
                ta = tab[ia][0]
            else:
                ta = 0
            if len(bi):
                ib = bi[-1]
                tb = tab[ib][0]
            else:
                tb = 0
            if t <= ta + tb:
                tot_time = tot_time - ta - tb + t
                if len(ai):
                    read[ia] = 0
                    ai.pop()
                if len(bi):
                    read[ib] = 0
                    bi.pop()
                read[i] = 1

if ka >= k and kb >= k:
    bc = read.count(1)
    if bc < m:
        for i in range(n):
            if read[i] == 0:
                read[i] = 1
                bc += 1
                tot_time += tab[i][0]
            if bc == m:
                break
    elif bc > m:
        for i in range(n):
            t, a, b, tabi = tab[i]
            if a and b and read[i] == 0:
                if len(ai) != len(bi):
                    print('error')
                    exit()
                if len(ai) and len(bi):
                    ia = ai[-1]
                    ib = bi[-1]
                    tot_time += t - tab[ai.pop()][0] - tab[bi.pop()][0]
                    bc -= 1
                    read[i] = 1
                    read[ia] = 0
                    read[ib] = 0
                else:
                    break
            if bc == m:
                break
    if bc != m:
        print(-1)
    else:
        print(tot_time)
        ans = []
        for i in range(n):
            if read[i]:
                ans.append(tab[i][3])
        print(*ans)
else:
    print(-1)
