line = input()
n, m, k = [int(i) for i in line.split(' ')]
books, allL, aliceL, bobL, other =list(range(1, n + 1)), [], [], [], []
ts = [[] for _ in range(n + 1)] 
for i in range(n):
    line = input()
    t, a, b = [int(j) for j in line.split(' ')]
    ts[i + 1] = [t, a, b]
    if a == 1 and b == 1:
        allL.append(i + 1)
    if a == 1:
        aliceL.append(i + 1)
    if b == 1:
        bobL.append(i + 1)

if min(len(aliceL), len(bobL)) < k or (len(allL) < k and 2 * (k - len(allL)) > m - len(allL)) :
    print(-1)
    exit()

books.sort(key=lambda x: ts[x][0])
allL.sort(key=lambda x: ts[x][0])
aliceL.sort(key=lambda x: ts[x][0])
bobL.sort(key=lambda x: ts[x][0])

aset = set(aliceL[:k])
bset = set(bobL[:k])
cset = aset | bset
if len(cset) < m:
    for i in books:
        if i not in cset:
            cset.add(i)
            if len(cset) == m:
                break
elif len(cset) > m:
    la, lb = k - 1, k - 1 
    for i in allL:
        if i not in cset and ts[i][1] + ts[i][2] == 2:
            cset.add(i)
            while la >= 0:
                if ts[aliceL[la]][2] == 0:
                    break
                la -= 1
            while lb >= 0:
                if ts[bobL[lb]][1] == 0:
                    break
                lb -= 1
            cset.remove(aliceL[la])
            cset.remove(bobL[lb])
            if (n, m, k) == (6561, 810, 468):
                print(la, lb, len(cset))
            la -= 1
            lb -= 1
            if len(cset) == m:
                break
if len(cset) != m:
    print(-1)
    exit()
print (sum(ts[i][0] for i in cset))
for i in cset:
    print(i, end=' ')






