n , m, k = map(int,input().split())
a = [list(map(int,input().split())) for  i in range(n)]
b = sorted(a,key = lambda x : x[0])
l = [] ; n1 = k ;n2 = k
s = 0
t = m-2*k
for i in range(n) :
    if m == 0 or (n1 == 0 and n2 == 0) : break
    if b[i][1] == 0 and b[i][2] == 0 and t > 0 and m-1 >= max(n1,n2) :
        l.append(a.index(b[i])+1)
        s+= b[i][0] 
        m -= 1 ; t-= 1
    elif b[i][1] == 1 and b[i][2] == 1 and  m-1 >= max(n1-1,n2-2) :
        l.append(a.index(b[i])+1)
        s+= b[i][0] 
        m -= 1  ; n1 -= 1 ; n2 -= 1 
    elif  b[i][1] == 0 and b[i][2] == 1  and m-1 >= max(n1,n2-1) :
        l.append(a.index(b[i])+1)
        s+= b[i][0] 
        m -= 1  ;  n2 -= 1 
    elif  b[i][1] == 1 and b[i][2] == 0 and m-1 >= max(n1-1,n2):
        l.append(a.index(b[i])+1)
        s+= b[i][0] 
        m -= 1  ;  n1 -= 1   
if n1 <= 0 and n2 <= 0 : 
    print(s ) ; print(*l)      
else : print(-1)          