n, m, k = [int(i) for i in input().split()]

doub = []; a = []; b = []; dis = []
for i in range(n):
    ti, ai, bi = [int(i) for i in input().split()]

    if ai and bi:
        doub.append((ti, i))
    
    elif ai:
        a.append((ti, i))
    
    elif bi:
        b.append((ti, i))

    else:
        dis.append((ti, i))

doub.sort(); a.sort(); b.sort()
# print(doub, a, b, sep="\n")

time = 0

i = 0; j = 0
while i+j < k:
    if (i < len(doub)):
        db = doub[i][0]
    else:
        db = 100000
    if (j < len(a) and j < len(b) and (i+2*j) <= (m-2)):
        sing = a[j][0] + b[j][0]
    else:
        sing = 100000
    
    if (db <= sing):
        time += db
        i += 1 
    else:
        time += sing
        j += 1

used = doub[:i] + a[:j] + b[:j]

# print(used)

fim = doub[i:] + a[j:] + b[j:] + dis
fim.sort()

for i in range(m-2*k):
    time += fim[i][0]
    used.append(fim[i])

if (len(doub) + min(len(a), len(b))) >= k:
    print(time)

    #used.extend(fim[:m-2*k])
    for i in used:
        print(i[1]+1, end=" ")
    print()

else:
    print(-1)



