from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue


# sys.setrecursionlimit(200000)
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline


def input():
    return sys.stdin.readline().strip()


def iinput():
    return int(input())


def tinput():
    return input().split()


def rinput():
    return map(int, tinput())


def rlinput():
    return list(rinput())


mod = int(1e9)+7


def factors(n):
    return set(reduce(list.__add__,
                      ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))


# ----------------------------------------------------
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
def pre(a):
    if len(a) == 0:
        return []
    ans = [a[0][0]]
    for i in range(1, len(a)):
        ans.append(ans[-1] + a[i][0])
    return ans

t = 1
# t = iinput()
oo = []
zo = []
oz = []
zz = []
for _ in range(t):
    n,m, k = rinput()
    for i in range(n):
        t, a, b = rinput()
        if a == 1 and b == 1:
            oo.append((t,i))
        elif a == 1:
            oz.append((t,i))
        elif b==1:
            zo.append((t, i))
        else:
            zz.append((t,i))
oo.sort()
zo.sort()
oz.sort()
zz.sort()
poo = pre(oo)
pzo = pre(zo)
poz = pre(oz)
noo = len(oo)
nzo = len(zo)
noz = len(oz)
ans = float('inf')
config = [0, 0, 0]  #oo,oz,zo
for i in range(noo+1):
    want = k - i
    if nzo >= want and noz >= want and want > 0 and i==0:
        val = pzo[want - 1] + poz[want - 1]
        if val <= ans and 2*want<=m:
            ans = val
            config = [0,want,want]
            
    if nzo >= want and noz >= want and i > 0 and want > 0:
        val = poo[i - 1] + pzo[want - 1] + poz[want - 1]
        if val <= ans and i+2*want<=m:
            ans=val
            config=[i, want, want]
        
    if want == 0 and i==k:
        val = poo[i - 1]
        if val <= ans and i<=m:
            ans=val
            config=[i, 0, 0]


if ans == float('inf'):
    print(-1)
else:
    items = sum(config)
    ioo,ioz,izo = config
    newarr = oo[ioo:] + oz[ioz:] + zo[izo:] + zz
    newarr.sort()
       
    fans = []
    for i in range(config[0]):
        fans.append(oo[i][1] + 1)
    for i in range(config[1]):
        fans.append(oz[i][1] + 1)
    for i in range(config[2]):
        fans.append(zo[i][1] + 1)
    
    for i in range(m - items):
        ans+=newarr[i][0]
        fans.append(newarr[i][1]+1)
    print(ans)
    print(*fans)




