import pdb
tmp = input()
lst = tmp.split(' ')
n = int(lst[0])
m = int(lst[1])
k = int(lst[2])

i=0

alice = []
bob = []
common_arr =[]
alice_count = 0
bob_count = 0
indexDict = {}
final = []

while (i<n):
	tmp = input()
	lst = tmp.split(' ')
	t = int(lst[0])
	a = int(lst[1])
	b = int(lst[2])
	tmp = (t,a,b)
	indexDict[(t,a,b)] = i
	final.append(tmp)

	if(a==1 and b==1):
		common_arr.append(tmp)
		alice_count += 1
		bob_count += 1
		i+=1
		continue
	elif(a==1 and b!=1):
		alice.append(tmp)
		alice_count+=1
		i+=1
		continue
	elif(a!=1 and b == 1):
		bob.append(tmp)
		bob_count+=1
		i+=1
		continue
	i+=1

if(alice_count<k or bob_count<k):
	print(-1)

else:
	alice.sort(key = lambda x:x[0])
	bob.sort(key = lambda x:x[0])
	common_arr.sort(key = lambda x:x[0])
	# pdb.set_trace()
	booksA = k
	booksB = k
	a=0
	b=0
	c=0
	lenA = len(alice)-1
	lenB = len(bob)-1

	lenC = len(common_arr)
	finalPosLst = []
	sum = 0

	while (True):
		if(booksA == 0 and booksB == 0):
			break

		if(a>=lenA):
			sum += common_arr[c][0]
			booksA = booksA -1
			booksB = booksB -1
			finalPosLst.append(indexDict[common_arr[c]])
			c+=1
			m = m-1
			continue

		if(b>=lenB):
			sum += common_arr[c][0]
			booksA = booksA -1
			booksB = booksB -1
			finalPosLst.append(indexDict[common_arr[c]])
			c+=1
			m =m-1
			continue

		if(c>=lenC):
			sum += alice[a][0]
			sum += bob[b][0]
			booksA = booksA -1
			booksB = booksB -1
			finalPosLst.append(indexDict[alice[a]])
			finalPosLst.append(indexDict[bob[b]])
			a+=1
			b+=1
			m =m-2
			continue

		if(alice[a]+bob[b]<common_arr[c]):
			sum += alice[a][0]
			sum += bob[b][0]
			booksA = booksA -1
			booksB = booksB -1
			finalPosLst.append(indexDict[alice[a]])
			finalPosLst.append(indexDict[bob[b]])
			a+=1
			b+=1
			m =m-2
		else:
			sum += common_arr[c][0]
			booksA = booksA -1
			booksB = booksB -1
			finalPosLst.append(indexDict[common_arr[c]])
			c+=1
			m =m-1
	# pdb.set_trace()
	finalPosLst = sorted(finalPosLst,reverse = True)
	# pdb.set_trace()
	for val in finalPosLst:
		final.pop(val)

	final.sort(key = lambda x:x[0])

	i = 0
	# pdb.set_trace()
	while(i<m):
		sum += final[i][0]
		finalPosLst.append(indexDict[final[i]])
		i = i+1

	i=0
	while (i<len(finalPosLst)):
		finalPosLst[i]+=1
		i+=1

	print(sum)
	print(*finalPosLst)
