import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *	
from heapq import *
from math import *
from itertools import permutations 
 
def eprint(*args):
    print(*args, file=sys.stderr)
zz=1
 
#sys.setrecursionlimit(10**6)
if zz:
	input=sys.stdin.readline
else:	
	sys.stdin=open('input.txt', 'r')
	sys.stdout=open('all.txt','w')
def li():
	return [int(x) for x in input().split()]
def fi():
	return int(input())
def si():
	return list(input().rstrip())	
def mi():
	return 	map(int,input().split())	
def gh():
	sys.stdout.flush()
def graph(n,m):
	for i in range(m):
		x,y=mi()
		a[x].append(y)
		a[y].append(x)
def bo(i):
	return ord(i)-ord('a')


n,m,k=mi()
a=[]
rr=[]
for i in range(n):
	p=li()
	a.append(p+[i+1])
	if p[1]+p[2]==2:
		rr.append(p+[i+1])
a.sort()
rr.sort()

c=d=ans=0
c1=[]
d1=[]
r=0
l=[]
#print(a)
for i in range(n):
	if a[i][1:3]==[0,1]:
		if d+r>=k:
			continue
		ans+=a[i][0]
		d1.append([a[i][0],a[i][3]])
		d+=1

	elif a[i][1:3]==[1,0]:
		if c+r>=k:
			continue
		ans+=a[i][0]
		c1.append([a[i][0],a[i][3]])
		c+=1

	elif a[i][1:3]==[1,1]:
		
		#ans+=a[i][0]

		if c+r>=k and d+r>=k and len(c1)>0 and len(d1)>0:
			#print("lol")
			if c1[-1][0]+d1[-1][0]>a[i][0]:
				#print("LOL",ans)
				r+=1
				c-=1
				d-=1
				ans-=(c1[-1][0]+d1[-1][0])
				l.append([a[i][0],a[i][3]])
				ans+=a[i][0]
				c1.pop()
				d1.pop()
				continue
		if c+r<k or d+r<k:
			r+=1
			ans+=a[i][0]	
			l.append([a[i][0],a[i][3]])	
		if c+r>k:
			ans-=c1[-1][0]
			c-=1
			c1.pop()
			#l.append([a[i][0],a[i][3]])
			#ans+=a[i][0]
		if d+r>k:
			ans-=d1[-1][0]
			d-=1
			d1.pop()
			#ans+=a[i][0]
	#print(c+r,d+r,r,ans,c1,d1,l)			

	if r>=k:
		break		
	
fin=c1+d1+l
#print(c1,d1,l)
if not (c+r>=k and d+r>=k):
	print(-1)
	exit(0)
if len(fin)<m:
	dd={}
	#print("LOL")
	for i in fin:
		dd[i[1]]=1
	j=m-len(fin)
	i=0	
	#print(ans,j,fin)
	#print(dd)
	while j>0 and i<n:
		if a[i][3] in dd:
			i+=1
			continue
		ans+=a[i][0]
		dd[a[i][3]]=1
		i+=1
		j-=1

	print(ans if c+r>=k and d+r>=k and j==0 else -1)	
	if c+r>=k and d+r>=k and j==0:
		for i in dd:
			print(i,end=' ')			
else:
	j=len(fin)-m
	dd={}
	for i in fin:
		dd[i[1]]=1
	for i in range(len(rr)):
		if j==0:
			break
		z=0	
		if len(c1) and len(d1):	
			ans+=rr[i][0]-c1[-1][0]-d1[-1][0]
			dd[c1[-1][1]]=0
			dd[d1[-1][1]]=0
			dd[rr[i][3]]=1
			c1.pop()
			d1.pop()	
			j-=1
		if len(c1) and c1[-1][0]>rr[i][0]:
			dd[c1[-1][1]]=0
			dd[rr[i][3]]=1
			c1.pop()	
		if len(d1) and d1[-1][0]>rr[i][0]:
			dd[d1[-1][1]]=0
			dd[rr[i][3]]=1
			d1.pop()	
	print(ans if j==0 else -1)
	if ans==82207:
		print("LOL")
	if j==0:
		for i in dd:
			if dd[i]==1:
				print(i,end=" ")		
