n,m,k = map(int,input().split())
ab = []
a = []
b = []
other = []
l = [list(map(int,input().split())) for i in range(n)]
for i in range(n):
    t,c,d = l[i]
    if c and d == 0:
        a.append([t,i+1])
    elif d and c == 0:
        b.append([t,i+1])
    elif c*d:
        ab.append([t,i+1])
    else:
        other.append([t,i+1])
def acc(x):
    d = [0]
    for i,j in x:
        d.append(d[-1]+i)
    return d
a.sort()
b.sort()
ab.sort()
other.sort()
sa = acc(a)
sb = acc(b)
sab = acc(ab)
so = acc(other)
la = len(a)
lb = len(b)
lab = len(ab)
lo = len(other)
if lb > la:
    la,lb = lb,la
    a,b = b,a

ans = float("INF")
ind = -1
for i in range(k+1):
    nab = i
    na = k-i
    no = m-2*na-nab
    if nab > lab or na > lb or no < 0 or no > lo:
        continue
    count = sa[na]+sb[na]+sab[nab]+so[no]
    if count < ans:
        ans = count
        ind = nab
if ind == -1:
    print(-1)
else:
    nab = ind
    na = k-ind
    no = m-2*na-nab
    lis = []
    for i,j in a[:na]:
        lis.append(j)
    for i,j in b[:na]:
        lis.append(j)
    for i,j in ab[:nab]:
        lis.append(j)
    for i,j in other[:no]:
        lis.append(j)
    print(ans)
    print(*lis)



