book, m, k = map(int, input().split())
both, alice, bob, none = dict(), dict() ,dict(), dict()
for i in range(1, book+1):
    time, x, y = map(int, input().split())
    if x == 1 and y == 1:
        both[i] = time
    elif x == 1 and y == 0:
        alice[i] = time
    elif x == 0 and y == 1:
        bob[i] = time
    else:
        none[i] = time
#manmohan
p1 = min(k, len(both))
p2 = k - p1
if 2*k - p1 > m or p2 > min(len(alice), len(bob)):
	print(-1)
else:
    both = sorted(both.items(), key = lambda x: x[1])
    alice = sorted(alice.items(), key = lambda x: x[1])
    bob = sorted(bob.items(), key = lambda x: x[1])
    none = sorted(none.items(), key = lambda x: x[1])
    count, x, y, z, temp = 0, 0, 0, 0, 0
    check, index, ids = [], [], []
    time = 0
    while count < k:
        if  x < len(both) and y < len(alice) and z < len(bob) and both[x][1] <= alice[y][1] + bob[z][1]:
            temp += 1
            count += 1
            time += both[x][1]
            check.append([x])
            x += 1
            continue
        elif x >= len(both) and y < len(alice) and z < len(bob):
            temp += 2
            count += 1
            time += alice[y][1] + bob[z][1]
            check.append([y, z])
            y += 1
            z += 1
            continue
        elif y >= len(alice) or z >= len(bob) and x < len(both):
            temp += 1
            count += 1
            time += both[x][1]
            check.append([x])
            x += 1
            continue

        elif y < len(alice) and z < len(bob):
            temp += 2
            count += 1
            time += alice[y][1] + bob[z][1]
            check.append([y, z])
            y += 1
            z += 1
    if temp >= m:
        l = len(check)-1
        while temp > m-2 and l >= 0:
            if len(check[l]) == 2 and x < len(both):
                time -= alice[check[l][0]][1] + bob[check[l][1]][1]
                time += both[x][1]
                check.append([x])
                x += 1
                temp -= 1
                count -= 1
                check.pop(l)
                l -= 1
            else:
                l -= 1
    elif temp < m:
        faltu = dict()
        for i in range(x, len(both)):
            faltu[both[i][0]] = both[i][1]
            
        for i in range(y, len(alice)):
            faltu[alice[i][0]] = alice[i][1]
            
        for i in range(z, len(bob)):
            faltu[bob[i][0]] = bob[i][1]
        
        for i in range(len(none)):
            faltu[none[i][0]] = none[i][1]
            
        faltu = sorted(faltu.items(), key = lambda x: x[1])
        
        for i in range(m - temp):
            time += faltu[i][1]
            ids.append(faltu[i][0])

            
    print(time)
    for i in check:
        if len(i) == 2:
            print(alice[i[0]][0], bob[i[0]][0], end = ' ')
        else:
            print(both[i[0]][0], end = ' ')

    for i in ids:
        print(i, end = ' ')
