n,m,k=map(int,input().split())
both,alice,bob,noone,index=[],[],[],[],[]
alicetime,bobtime,count=0,0,0
for i in range(n):
    t,a,b=map(int,input().split())
    if a==1 and b==1:
        both.append([t,i+1])
    elif a==1 and b==0:
        alice.append([t,i+1])
    elif a==0 and b==1:
        bob.append([t,i+1])
    else:
        noone.append([t,i+1])
both.sort(reverse=True)
alice.sort(reverse=True)
bob.sort(reverse=True)
noone.sort(reverse=True)
if m==k:
    while len(both)>0 and m>0 and alicetime<k and bobtime<k:
        x=both.pop()
        m-=1
        alicetime+=1
        bobtime+=1
        count+=x[0]
        index.append(x[1])
    if alicetime!=k or bobtime!=k:
        print(-1)
    else:
        print(count)
        print(*index)
else:
    while len(both)>0 and len(alice)>0 and len(bob)>0 and m>0 and alicetime<k and bobtime<k:
        if both[-1][0]<=alice[-1][0]+bob[-1][0]:
            x=both.pop()
            count+=x[0]
            index.append(x[1])
            alicetime+=1
            bobtime+=1
            m-=1
        else:
            if m>=2:
                if both[-1][0]>=alice[-1][0]+bob[-1][0]:
                    y=alice.pop()
                    z=bob.pop()
                    count+=(y[0]+z[0])
                    index.append(y[1])
                    index.append(z[1])
                    m-=2
                    alicetime+=1
                    bobtime+=1
            else:
                break           
    if len(both)==0 and len(alice)>0 and len(bob)>0 and m>0 and alicetime<k and bobtime<k:
        while len(alice)>0 and len(bob)>0 and m>=2 and alicetime<k and bobtime<k:
            y=alice.pop()
            z=bob.pop()
            count+=(y[0]+z[0])
            index.append(y[1])
            index.append(z[1])
            m-=2
            alicetime+=1
            bobtime+=1
    elif len(both)>0 and (len(alice)>=0 or len(bob)>=0) and m>0 and alicetime<k and bobtime<k:
        while len(both)>0 and m>0 and alicetime<k and bobtime<k:
            x=both.pop()
            count+=x[0]
            index.append(x[1])
            alicetime+=1
            bobtime+=1
            m-=1       
    if alicetime==k and bobtime==k and m>0:
        l=both+alice+bob+noone
        l.sort(reverse=True) 
        while m>0 and len(l)>0:
            x=l.pop()
            count+=x[0]
            index.append(x[1])
            m-=1
    #print(alicetime,bobtime,m)        
    if alicetime!=k or bobtime!=k or m!=0:
        print(-1)
    else:
        print(count)
        print(*index)