from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
 
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]


n,m,k = li()

alice = []
bob = []
both = []
rem = []

for i in range(n):
    a,b,c = li()
    if b and c:
        both.append([a,i])
    elif b:alice.append([a,i])
    elif c:bob.append([a,i])
    else:rem.append([a,i])

alice.sort()
bob.sort()
rem.sort()
both.sort()

l = set()
k1 = k
k2 = k
ind = time = 0

for i in both:
    ind += 1
    time += i[0]
    l.add(i[1])
    m -= 1
    k1 -= 1
    k2 -= 1
    if not m:
        if not k1 and not k2:
            print(time)
            for i in l:print(i + 1,end = ' ')

        else:
            print(-1)
        exit()

rem.extend(both[ind:])
both = both[:ind]
i = 0
n1 = min(len(alice),len(bob))

# print(l,m,k1,k2)
while i < n1 and k1:

    time += alice[i][0] + bob[i][0]
    l.add(alice[i][1])
    l.add(bob[i][1])

    k1 -= 1
    k2 -= 1
    m -= 2
    i += 1
    if not m or not k1:break
# print(l,m,k1,k2)
while i < n1 and len(both) and m:
    if alice[i][0] + bob[i][0] < both[-1][0]:
        l.remove(both[-1][1])
        time -= both[-1][0]
        rem.append(both.pop())
        l.add(alice[i][1])
        l.add(bob[i][1])
        time += alice[i][0] + bob[i][0]
        m -= 1
    else:break

    i += 1

# print(l,m,k1,k2)

rem.extend(alice[i:])
rem.extend(bob[i:])
rem.sort()
rem.reverse()


while m > 0 and len(rem):
    l.add(rem[-1][1])
    time += rem.pop()[0]
    m -= 1

if not m and not k1 and not k2:
    print(time)
    for i in l:print(i + 1,end = ' ')
else:print(-1)
