n,m,k = map(int, input().split())
oo = list()
oa = list()
ob = list()
zz = list()
for i in range(n):
	t,a,b = map(int, input().split())
	if a == 1 and b == 1:
		oo.append((t,i))
	elif a == 0 and b == 1:
		ob.append((t,i))
	elif a == 1 and b == 0:
		oa.append((t,i))
	else:
		zz.append((t,i))

oo = sorted(oo)
oa = sorted(oa)
ob = sorted(ob)

oo_p = 0
oa_p = 0
ob_p = 0

ca = 0
cb = 0
ans = 0
ans_arr = list()
MAX = 23942034809238409823048

def condition(k, loa, lob, loo, m): 
	print(k, loa, lob, loo, m)
	if (max(k-loa, k-lob) > loo or max(k-loa, k-lob) > m):
		return False
	return True

def get_first_elem_from_list(l, pos):
	if pos < len(l):
		return l[pos]
	else:
		return (MAX,-1)

def remove_first_elem_from_list(l, pos):
	if len(l)>pos:
		pos += 1
	return pos

if not condition(k, len(oa), len(ob), len(oo), m):
	print("-1")
	exit(0)

while ca < k or cb < k:
	oo_f = get_first_elem_from_list(oo, oo_p)
	oa_f = get_first_elem_from_list(oa, oa_p)
	ob_f = get_first_elem_from_list(ob, ob_p)
	print(oo_f, oa_f, ob_f)
	if ca < k and cb < k:
		if oo_f[0] <= oa_f[0] + ob_f[0] or not condition(k-oo_p-oa_p-1, len(oa)-oa_p-1, len(ob) - ob_p -1, len(oo) - oo_p, m - oo_p - oa_p - ob_p - 2):
			if oo_f[0] == MAX:
				print("-1")
				exit(0)
			ca += 1
			cb += 1
			ans+=oo_f[0]
			ans_arr.append(oo_f[1])
			oo_p = remove_first_elem_from_list(oo, oo_p)
		else:
			ca += 1
			cb += 1
			ans+=oa_f[0]+ob_f[0]
			ans_arr.extend([oa_f[1], ob_f[1]])
			oa_p = remove_first_elem_from_list(oa, oa_p)
			ob_p = remove_first_elem_from_list(ob, ob_p)
	elif ca < k:
		if oo_f[0] <= oa_f[0]:
			ca += 1
			ans+=oo_f[0]
			ans_arr.append(oo_f[1])
			oo_p = remove_first_elem_from_list(oo, oo_p)
		else:
			ca += 1
			ans+=oa_f[0]
			ans_arr.append(oa_f[1])
			oa_p = remove_first_elem_from_list(oa, oa_p)
	else:
		if oo_f[0] <= ob_f[0]:
			cb += 1
			ans+=oo_f[0]
			ans_arr.append(oo_f[1])
			oo_p = remove_first_elem_from_list(oo, oo_p)
		else:
			cb += 1
			ans+=ob_f[0]
			ans_arr.append(ob_f[1])
			ob_p = remove_first_elem_from_list(ob, ob_p)

if len(ans_arr) < m:
	zz.extend(oo[oo_p:])
	zz.extend(oa[oa_p:])
	zz.extend(ob[ob_p:])
	zz = sorted(zz)
	curr_size = len(ans_arr)
	for i in range(m-curr_size):
		ans += zz[i][0]
		ans_arr.append(zz[i][1])

assert len(ans_arr) == m
print(ans)
for i in ans_arr:
	print(i + 1, end =" ")

