n,m,k=list(map(int,input().split()))
l,l1,l2,l3=[],[],[],[] 
for i in range(1,n+1):
    x,y,z=list(map(int,input().split()))
    if y==1 and z==1:
        l.append([x,i,-1])
    elif y==1:
        l1.append([x,i,0])
    elif z==1:
        l2.append([x,i,0])
    else:
        l3.append([x,i,0])
if 2*k<m:
    l1.sort()
    l2.sort()
    a=len(l1)
    b=len(l2)
    for i in range(min(a,b,k)):
        x=l1.pop(0)
        y=l2.pop(0)
        x[2]=y[1]
        x[0]+=y[0]
        l.append(x)
    p=[]
    l.sort()
    i=0
    book=0
    while i!=k and l!=[]:
        z=l.pop(0)
        p.append(z)
        if z[2]==-1:
            book+=1
        else:
            book+=2
        i+=1
    if len(p)<k:
        print(-1)
    else:
        l=l+l1+l2+l3
        l.sort()
        p=p+l[:m-book]
        l=[]
        c=0
        for i,j,k in p:
            c+=i
            if k!=-1 and k!=0:
                l.extend([j,k])
            else:
                l.append(j)
        print(c)
        print(*l)
elif 2*k>m:
        l1.sort()
        l2.sort()
        l.sort()
        b=[]
        i=0
        p=[]
        while i!=k:
            if l!=[] and l1!=[] and l2!=[]:
                if l[0]<l1[0]+l2[0]:
                    z=l.pop(0)
                    b.append(z)
                    i+=1
                else:
                    if i+2<=k:
                        x=l1.pop(0)
                        y=l2.pop(0)
                        x[2]=y[1]
                        x[0]+=y[0]
                        b.append(x)
                        i+=2
                    else:
                        z=l.pop(0)
                        b.append(z)
                        i+=1
            elif l==[]:
                if l1!=[] and l2!=[]:
                        x=l1.pop(0)
                        y=l2.pop(0)
                        x[2]=y[1]
                        x[0]+=y[0]
                        b.append(x)
                        i+=2
                else:
                    break
            else:
                if l!=[]:
                    z=l.pop(0)
                    b.append(z)
                    i+=1
                else:
                    break
                
        if len(p)<k:
            print(-1)
        else:
                
            z=l+l1+l2+l3 
            p=b+z[:m-k]
            c=0
            l=[]
            for i,j,k in p:
                c+=i
                if k!=-1 and k!=0:
                    l.extend([j,k])
                else:
                    l.append(j)
            print(c)
            print(*l)
    
    
else:
    l1.sort()
    l2.sort()
    x=l1[:k]+l2[:k]
    if len(x)==m:
        c=0
        k=[]
        for i,j,k5 in x:
            c+=i
            k.append(j)
        print(c)
        print(*k)
    else:
        print(-1)
        
