import sys
import random
from math import *
 
def input():
    return sys.stdin.readline().strip()
 
def iinput():
    return int(input())

def finput():
    return float(input())

def tinput():
    return input().split()

def linput():
    return list(input())
 
def rinput():
    return map(int, tinput())

def fiinput():
    return map(float, tinput())
 
def rlinput():
    return list(map(int, input().split()))
def trinput():
    return tuple(rinput())

def srlinput():
    return sorted(list(map(int, input().split())))

def NOYES(fl):
    if fl:
        print("NO")
    else:
        print("YES")
def YESNO(fl):
    if fl:
        print("YES")
    else:
        print("NO")
    
def main():  
    #n = iinput()
    #k = iinput() 
    #m = iinput() 
    #n = int(sys.stdin.readline().strip()) 
    #n, k = rinput()
    #n, m = rinput()
    #m, k = rinput()
    #n, k, m = rinput()
    n, m, k = rinput()
    #k, n, m = rinput()
    #k, m, n = rinput() 
    #m, k, n = rinput()
    #m, n, k = rinput()
    #q = srlinput()
    #q = linput()
    q = []
    f = [i + 1 for i in range(n)]
    for i in range(n):
        q.append(rlinput())
    for i in range(n - 1):
        for j in range(n - i - 1):
            if q[j][0] > q[j + 1][0]:
                q[j], q[j + 1] = q[j + 1], q[j]
                f[j], f[j + 1]=  f[j + 1], f[j]
    w,e,r, fak,pr,pe,pw,fe,fr,fw = [], [], [], [], [0],[0],[0], [], [], []
    res1, res2, c = 0, 0, 0
    for i in range(n):
        res1, res2 = res1 + q[i][1], res2 + q[i][2]
        if q[i][1] and q[i][2]:
            w.append(q[i][0])
            pw.append(w[-1] + pw[-1])
            fw.append(f[i])
        elif q[i][1]:
            e.append(q[i][0])
            pe.append(e[-1] + pe[-1])  
            fe.append(f[i])
        elif q[i][2]:
            r.append(q[i][0])
            pr.append(r[-1] + pr[-1])    
            fr.append(f[i])
        else:
            fak.append(q[i][0])   
    if min(res1, res2) < k:
        print(-1)
    else:
        res = 5e9
        for i in range(1 + min(k, len(w))):
            if k - i <= min(len(r), len(e)):
                t = pw[i] + pr[k - i] + pe[k - i]
                if t <= res:
                    c = i
                    res = t
        dell = sorted(fw[:c] + fe[: c + k] + fr[: k + c], reverse = True)
        for i in dell:
            rt = f.index(i)
            del q[rt]
            del f[rt]      
        for i in range(m - 2 * k + c):
            dell.append(f[i])
            res += q[i][0]
        print(res)
        print(*dell)
    
                
        
    
            
    
    

    
for inytd in range(1):
    main()