import sys

s = sys.stdin.readline().split()
n, m, k = int(s[0]), int(s[1]), int(s[2])

all = []
All = []
Alice = []
Bob = []
Both = []
none = []
z = 1

while n:
    i = sys.stdin.readline().split()
    x = 3
    i.append(z)
    while x:
        i[x - 1] = int(i[x - 1])
        x -= 1
    all.append(i)
    if i[1] == i[2]:
        if i[1] == 0:
            none.append(i)
        else:
            Both.append(i)
    else:
        if i[1] == 0:
            Bob.append(i)
        else:
            Alice.append(i)
    z += 1
    n -= 1

Alice.sort(key=lambda x: x[0])
Bob.sort(key=lambda x: x[0])
Both.sort(key=lambda x: x[0])
none.sort(key=lambda x: x[0])

if 2 * k > m:
    l = 2 * k - m
    if len(Both)>=l:
        tresult = Both[:l]
        Both = Both[l:]
        All = Alice + Both + Bob + none
        m = 2 * (m - k)
        k = k - l
    else:
        print(-1)
        exit()
else:
    tresult = []

resulta = []
resultb = []

if k > 0:
    aaa = Alice + Both
    aaa.sort(key=lambda x: x[0])
    if len(aaa) >= k:
        resulta = aaa[:k]
    else:
        print(-1)
        exit()
    col_totals1 = [sum(x) for x in zip(*resulta)]
    xx = col_totals1[2]
    yy = k - xx

    Both = Both[xx:]
    Alice = Alice[yy:]


    k = k - xx
    if k > 0:
        bbb = Bob + Both
        bbb.sort(key=lambda x: x[0])
        if len(bbb) >= k:
            resultb = bbb[:k]
        else:

            print(-1)
            exit()
        col_totals2 = [sum(x) for x in zip(*resultb)]
        xx = col_totals1[1]
        yy = k - xx
        Both = Both[xx:]
        Bob = Bob[yy:]
q = len(resultb) + len(resulta)
q = m - q

All = Both + Alice + Bob + none
All.sort(key=lambda x: x[0])

result = All[:q]

result = resulta + resultb + result + tresult

result.sort(key=lambda x: x[0])
print(sum(row[0] for row in result))
print(' '.join([str(row[3]) for row in result]))