import math
def gcd(a,b): 
    if (b == 0): 
         return a 
    return gcd(b, a%b) 

def lcm(a,b): 
    return (a*b) / gcd(a,b) 

def bs(arr, l, r, x): 
    while l <= r: 
        mid = l + (r - l)//2; 
        if(arr[mid]==x): 
            return arr[mid]
        elif(arr[mid]<x): 
            l = mid + 1
        else: 
            r = mid - 1
    return -1

def swap(list, pos1, pos2): 
      
    list[pos1], list[pos2] = list[pos2], list[pos1] 
    return list

t = 1
for _ in range(t):
    n,m,k = map(int,input().split())
    x = []
    c=0
    ans=0
    y01 = []
    y10 = []
    y11 = []
    vis = []
    for i in range(n):
        tt,a,b = map(int,input().split())
        if(a==1 and b==1):
            y11.append((tt,i))
        elif(a==1 and b==0):
            y10.append((tt,i))
        elif(a==0 and b==1):
            y01.append((tt,i))
        vis.append((tt,0,i))
    y11.sort()
    y01.sort()
    y10.sort()

    f=0
    i = 0
    j = 0
    book = 0
    while(k):
        k-=1
        if(i<len(y11) and (j<len(y01) and j<len(y10))):
            if(y11[i][0]>y01[j][0]+y10[j][0] and book+2<=m):
                ans+=y10[j][0]+y01[j][0]
                vis[y01[j][1]] = (vis[y01[j][1]][0],1,vis[y01[j][1]][2])
                vis[y10[j][1]] = (vis[y10[j][1]][0],1,vis[y10[j][1]][2])
                book+=2
                j+=1
            else:
                ans+=y11[i][0]
                vis[y11[i][1]] = (vis[y11[i][1]][0],1,vis[y11[i][1]][2])
                book+=1
                i+=1
                
        elif(i<len(y11)):
            ans+=y11[i][0]
            vis[y11[i][1]] = (vis[y11[i][1]][0],1,vis[y11[i][1]][2])
            book+=1
            i+=1
        elif((j<len(y01) and j<len(y10))):
            ans+=y10[j][0]+y01[j][0]
            vis[y01[j][1]] = (vis[y01[j][1]][0],1,vis[y01[j][1]][2])
            vis[y10[j][1]] = (vis[y10[j][1]][0],1,vis[y10[j][1]][2])
            book+=2
            j+=1
        else:
            f=1
    # print(book)
    vis.sort()
    if(m-book>0):
        z = m-book
        x = 0
        while(z):
            if(x>len(vis)):
                f=1
                break
            if(vis[i][1]==0):
                ans+=vis[i][0]
                vis[i] = (vis[i][0],1,vis[i][2])
            x+=1
            z-=1
    # print(vis)
    if(f):
        print(-1)
        continue
    print(ans)
    for i in range(len(vis)):
        if(vis[i][1]==1):
            print(vis[i][2]+1, end=' ')
    print()
