from sys import stdin, setrecursionlimit, stdout
#setrecursionlimit(1000000)
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heappushpop, heapreplace
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())
#mod=1000000007
res=['YES', 'NO']
############# CODE STARTS HERE #############




test_case=1
while test_case:
    test_case-=1


    n, m, k=mi()
    both=[[0, 0]]
    al=[[0, 0]]
    bob=[[0, 0]]
    a=[]
    for i in range(n):
        x, y, z=mi()
        a.append([x, i+1])
        if y and z:
            both.append([x, i+1])
        elif y:
            al.append([x, i+1])
        elif z:
            bob.append([x, i+1])
    both.sort()
    for i in range(1, len(both)):
        both[i][0]+=both[i-1][0]
    al.sort()
    for i in range(1, len(al)):
        al[i][0]+=al[i-1][0]
    bob.sort()
    for i in range(1, len(bob)):
        bob[i][0]+=bob[i-1][0]

    ans=1000000000000000000000000000

    #print(both)
    #print(al)
    #print(bob)
    ind=-1
    for i in range(len(both)):
        if len(al)>k-i and len(bob)>k-i and i+k-i+k-i<=m:
            if both[i][0]+al[k-i][0]+bob[k-i][0]<ans:
                ans=both[i][0]+al[k-i][0]+bob[k-i][0]
                ind=i

            #print(both[:i]+al[:k-i]+bob[:k-i])
        if i==k<=m:
            if both[i][0]<ans:
                ans=both[i][0]
                ind=i
            break
    #print(ans)
    #print(-1 if ans==1000000000000000000000000000 else ans)
    if ans==1000000000000000000000000000:
        print(-1)
        exit()
    index=[]
    for i in range(1, ind+1):
        index.append(both[i][1])
    for i in range(1, k-ind+1):
        index.append(al[i][1])
        index.append(bob[i][1])
    if len(index)<m:
        a.sort()
        s=set(index)
        j=0
        z=len(index)
        while z<m:
            if a[j][1] not in s:
                index.append(a[j][1])
                ans+=a[j][0]
                z+=1
            j+=1
    print(ans)
    print(*index)