

n,m,k=map(int,input().split())
a,b,tog,non=[],[],[],[]
for i in range(n):
	t,x,y=map(int,input().split())
	if x==1 and y==1:
		tog.append([t,i])
	elif x==1 and y==0:
		a.append([t,i])
	elif x==0 and y==1:
		b.append([t,i])
	else:
		non.append([t,i])
ltog=len(tog)
la=len(a)
lb=len(b)
if ltog+la<k or ltog+lb<k:
	print(-1)
else:
	a.sort(reverse=True)
	b.sort(reverse=True)
	tog.sort(reverse=True)
	ca,cb=0,0
	res=0
	ans=[]
	while ca<k or cb<k:
		if tog:
			ptog=tog[-1][0]
		else:
			ptog=0
		if a:
			pa=a[-1][0]
		else:
			pa=0
		if b:
			pb=b[-1][0]
		else:
			pb=0
		if ca<k and cb<k:
			if pa and pb and ptog:
				if pa+pb<=ptog and len(ans)+2*(k-len(ans))<=m:
					res+=pa+pb
					ans.append(a.pop()[1]+1)
					ans.append(b.pop()[1]+1)
				else:	
					res+=ptog
					ans.append(tog.pop()[1]+1)
				ca+=1
				cb+=1
			elif ptog:
				res+=ptog
				ans.append(tog.pop()[1]+1)
				ca+=1
				cb+=1
			elif pa and pb:
				res+=pa+pb
				ans.append(a.pop()[1]+1)
				ans.append(b.pop()[1]+1)
				ca+=1
				cb+=1
			else:
				res=-1
				break
		else:
			if ca<k:
				if pa and ptog:
					if pa<ptog:
						res+=pa
						ans.append(a.pop()[1]+1)
						ca+=1
					else:	
						res+=ptog
						ans.append(tog.pop()[1]+1)
						ca+=1
						cb+=1
				elif ptog:
					res+=ptog
					ans.append(tog.pop()[1]+1)
					ca+=1
					cb+=1
				elif pa:
					res+=pa
					ans.append(a.pop()[1]+1)
					ca+=1
				else:
					res=-1
					break
			elif cb<k:
				if pb and ptog:
					if pb<ptog:
						res+=pb
						ans.append(b.pop()[1]+1)
						cb+=1
					else:	
						res+=ptog
						res.append(tog.pop()[1]+1)
						ca+=1
						cb+=1
				elif ptog:
					res+=ptog
					ans.append(tog.pop()[1]+1)
					ca+=1
					cb+=1
				elif pb:
					res+=pb
					ans.append(b.pop()[1]+1)
					cb+=1
				else:
					res=-1
					break
	if len(ans)==m:
		print(res)
		print(*ans)
	elif len(ans)<m:
		l=a+b+tog+non
		l.sort(reverse=True)
		x=m-len(ans)
		while x:
			x-=1
			res+=l[-1][0]
			ans.append(l.pop()[1]+1)
		print(res)
		print(*ans)
	else:
		print(-1)
