n, m, k = map(int, input().split())
books = []
booksA = []
booksB = []
booksAB = []
for ind in range(n):
    t, a, b = map(int, input().split())
    if a == 1 and b == 0:
        booksA.append((t, ind + 1))
    elif a == 0 and b == 1:
        booksB.append((t, ind + 1))
    elif a == 1 and b == 1:
        books.append((t, ind + 1))
    else:
        booksAB.append((t, ind + 1))

booksAB.sort(reverse=True)
booksA.sort(reverse=True)
booksB.sort(reverse=True)
books.sort(reverse=True)


def f():
    t = 0
    ind_books = []
    for ind in range(k):
        if not books:
            if (not booksA or not booksB):
                return -1, []
            else:
                if len(ind_books) == m - 1:
                    return -1, []

                bb1 = booksA.pop()
                bb2 = booksB.pop()
                ind_books.append(bb1[1])
                ind_books.append(bb2[1])
                t += bb1[0]
                t += bb2[0]

        elif len(ind_books) == m - 1 or ((not booksA or not booksB) or books[-1][0] <= booksA[-1][0] + booksB[-1][0]):
            bb = books.pop()
            ind_books.append(bb[1])
            t += bb[0]
        else:
            bb1 = booksA.pop()
            bb2 = booksB.pop()
            ind_books.append(bb1[1])
            ind_books.append(bb2[1])
            t += bb1[0]
            t += bb2[0]

    for _ in range(m - len(ind_books)):
        min_time = 1000000
        types = [books, booksA, booksB, booksAB]
        for b in types:
            if not b:
                continue
            else:
                if b[-1][0] < min_time:
                    min_time = b[-1][0]
        if min_time == 1000000:
            return -1
        for b in types:
            if not b:
                continue
            else:
                if b[-1][0] == min_time:
                    bb = b.pop()
                    ind_books.append(bb[1])
                    t += bb[0]
                    break
    return t, ind_books

time, indx = f()
print(time)
print(" ".join(map(str, indx)))