# -*- coding: utf-8 -*-
import math, string, itertools, operator, fractions, heapq, collections, re, array, bisect, sys, functools
def solve(line):
    n, m, k = map(int, line.split())
    a = []
    for i in range(n):
        a.append([int(x) for x in sys.stdin.readline().rstrip().split()])
    x, y, z, w = [], [], [], []
    for i in range(n):
        if a[i][1] == 1 and a[i][2] == 1:
            z.append((a[i][0], i))
        elif a[i][1] == 1:
            x.append((a[i][0], i))
        elif a[i][2] == 1:
            y.append((a[i][0], i))
        else:
            w.append((a[i][0], i))
    if len(x) + len(z) < k or len(y) + len(z) < k: print(-1);return
    x.sort()
    y.sort()
    z.sort()
    w.sort()
    ans = 0
    aa = set()
    i, j, k1 = 0, 0, 0
    k0 = k
    while k > 0:
        if i < len(x) and j < len(y) and k1 < len(z) and x[i][0] + y[j][0] < z[k1][0] and 2 + len(aa) <= m:
            aa.add(x[i][1])
            aa.add(y[i][1])
            i += 1
            j += 1
        elif k1 < len(z):
            aa.add(z[k1][1])
            k1 += 1
        elif 2 + len(aa) <= m:
            i += 1
            j += 1
            aa.add(x[i][1])
            aa.add(y[i][1])
        k -= 1
    k2 = 0
    if len(aa) > m: return -1
    while m > len(aa):
        aa.add(w[k2][1])
        k2 += 1
    ans = 0
    for i in aa:
        ans += a[i][0]
    print(ans)
    for idx, i in enumerate(aa):
        print(i + 1, end=(' ' if idx != len(aa) - 1 else '\n'))
    
t = 0
while True:
    line = sys.stdin.readline().rstrip()
    if not line:
        break
    solve(line)
    t += 1
