from heapq import *
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    inf = 10 ** 16
    n, m, k = MI()
    tab=LLI(n)
    tij=[(t,-a*2-b,j) for j,(t,a,b) in enumerate(tab)]
    tij.sort()
    hp=[[] for _ in range(4)]
    tot=0
    use=[False]*n
    cnt=[0]*4
    for t,i,j in tij:
        heappush(hp[-i],(-t,j))
        tot+=t
        use[j]=True
        cnt[-i]+=1
        if cnt[1]+cnt[3]>=k and cnt[2]+cnt[3]>=k and sum(cnt)>=m:
            break
    else:
        print(-1)
        exit()

    rem=[]
    for t,i,j in tij[sum(cnt):]:
        if i==-3:heappush(rem,(t,j))

    for _ in range(sum(cnt)-m):
        p=-1
        mx=-inf
        if cnt[0] and -hp[0][0][0]>mx:p=0;mx=-hp[0][0][0]
        if cnt[1]>k and -hp[1][0][0]>mx:p=1;mx=-hp[1][0][0]
        if cnt[2]>k and -hp[2][0][0]>mx:p=2;mx=-hp[2][0][0]
        if cnt[1] and cnt[2] and rem and -hp[1][0][0]-hp[2][0][0]-rem[0][0]>mx:p=3;mx=-hp[1][0][0]
        if p==-1:
            print(-1)
            exit()
        elif p<3:
            tot+=hp[p][0][0]
            use[hp[p][0][1]]=False
            heappop(hp[p])
            cnt[p]-=1
        else:
            tot+=hp[1][0][0]+hp[2][0][0]+rem[0][0]
            cnt[1]-=1
            cnt[2]-=1
            use[hp[1][0][1]]=False
            use[hp[2][0][1]]=False
            use[rem[0][1]]=True
            heappop(hp[1])
            heappop(hp[2])
            heappop(rem)

    print(tot)
    print(*[j+1 for j in range(n) if use[j]])

main()
