arr=[int(x) for x in input().split()]
size=arr[0]
max_books=arr[1]
constraint=arr[2]
book_dict={'11':[],'10':[],'01':[],'00':[]}
for i in range(size):
    book=input().split()
    if book[1]+book[2]=='00':
        book_dict['00'].append((str(i+1),int(book[0])))
    elif book[1]+book[2]=='10':
        book_dict['10'].append((str(i+1),int(book[0])))
    elif book[1]+book[2]=='01':
        book_dict['01'].append((str(i+1),int(book[0])))
    else:
        book_dict['11'].append((str(i+1),int(book[0])))
count11=len(book_dict['11'])
count10=len(book_dict['10'])
count01=len(book_dict['01'])
book_dict['00'].sort(key = lambda x: x[1])
book_dict['01'].sort(key = lambda x: x[1])
book_dict['10'].sort(key = lambda x: x[1])
result=0
indices=[]
if count11+count01>=constraint and count11+count10>=constraint:
    for i in range(min(count01,count10)):
        identity=book_dict['10'][i][0]+' '+book_dict['01'][i][0]
        value=book_dict['10'][i][1]+book_dict['01'][i][1]
        book_dict['11'].append((identity,value))
    book_dict['11'].sort(key = lambda x: x[1])
    count=0
    for i in range(len(book_dict['11'])):
        if len(book_dict['11'][i][0])!=1:
            tot=2
        else:
            tot=1
        if count+tot>max_books:
            continue
        else:
            count+=tot
            result+=book_dict['11'][i][1]
            if tot==1:
                indices.append(book_dict['11'][i][0])
            else:
                arr=book_dict['11'][i][0].split()
                indices.extend(arr)
            constraint-=1
        if constraint==0:
            break
    if constraint!=0:
        print(-1)
    else:
        if count==max_books:
            print(result)
            for i in indices:
                print(i,end=" ")
        else:
            book_dict['00'].extend(book_dict['01'])
            book_dict['00'].extend(book_dict['10'])
            book_dict['00'].sort(key = lambda x: x[1])
            for i in range(len(book_dict['00'])):
                if book_dict['00'][i][0] in indices:
                    continue
                else:
                    result+=book_dict['00'][i][1]
                    indices.append(book_dict['00'][i][0])
                    count+=1
                if count==max_books:
                    print(result)
                    for i in indices:
                        print(i,end=" ")
                    break
else:
    print(-1)