
import sys
# from collections import defaultdict
# t=1
# t=int(input())

def fun(x):
    # print(x)
    return x[0]

n,m,k=list(map(int,sys.stdin.readline().strip().split()))
xx=[]

a=[]
b=[]
c=[]
for i in range(n):
    # n=int(input())
    x=list(map(int,sys.stdin.readline().strip().split()))
    # a,b,c,d=list(sys.stdin.readline().strip().split())
    # n,k=list(map(int,sys.stdin.readline().strip().split()))
    # xx.append(x)
    
    if(x[1]==x[2]==1):
        a.append([x[0],i])
    elif(x[1]==1):
        b.append([x[0],i])
    elif(x[2]==1):
        c.append([x[0],i])
    
# a=k
# b=k
# # print(xx)
# xx.sort(key=fun)
# # print(xx)
# op=0

# for i in xx:
#     if()
ind=[]
b.sort(key=fun)
c.sort(key=fun)
for i in range(min(len(b),len(c))):
    a.append([b[i][0]+c[i][0],b[i][1],c[i][1]])
    
a.sort(key=fun)

d=b+c
# print(a,b,c,d)


# if(len(a)<k):
#     print(-1)
# else:
#     print(sum(a[:k]))
op=0

# print(a,b,c)
# print(a[0][1:])

for i in range(len(a)):
    if(k==0):
        break
    if(m>=len(a[i][1:])):
        m=m-len(a[i][1:])
        op+=a[i][0]
        ind+=a[i][1:]
        k=k-1
    if(k==0):
        break
# print(m)
if(m):
    d.sort(key=fun)
    for i in d:
        if(i[1] in ind):
            continue
        else:
            ind.append(i[1])
            op+=i[0]
            m=m-1
        if(m==0):
            break
if(m):
    print(-1)
else:
    print(op)
    print(*ind)
    