n, m, k = map(int, input().split())

common_books = []
alice_books = []
bob_books = []
disliked_books = []
durations = []

for i in range(n):
    duration, alice, bob = map(int, input().split())
    if alice and bob:
        collection = common_books
    elif alice:
        collection = alice_books
    elif bob:
        collection = bob_books
    else:
        collection = disliked_books
    collection.append(i)
    durations.append(duration)

def get0(collection, idx):
    if idx < len(collection):
        return durations[collection[idx]]
    return 0

def print_ans(idxs):
    idxs.sort()
    total = sum(durations[i] for i in idxs)
    print(total)
    print(' '.join(str(i + 1) for i in idxs))


if len(bob_books) + len(common_books) < k or len(alice_books) + len(common_books) < k:
    print(-1)
else:
    for collection in (common_books, alice_books, bob_books):
        collection.sort(key=lambda idx: durations[idx])
    icom = 0
    iali = 0
    ibob = 0
    idis = 0
    ncom = len(common_books)
    nali = len(alice_books)
    nbob = len(bob_books)
    ndis = len(disliked_books)

    total = 0
    for i in range(k):
        if icom < ncom and get0(alice_books, iali) + get0(bob_books, ibob) >= get0(common_books, icom):
            total += get0(common_books, icom)
            icom += 1
        elif iali < nali and ibob < nbob:
            total += get0(alice_books, iali)
            total += get0(bob_books, ibob)
            iali += 1
            ibob += 1
        else:
            total += get0(common_books, icom)
            icom += 1

    if m < icom + iali + ibob:
        for _ in range(icom + iali + ibob - m):
            if iali and ibob and icom != ncom:
                iali -= 1
                ibob -= 1
                total -= get0(alice_books, iali)
                total -= get0(bob_books, ibob)
                total += get0(common_books, icom)
                icom += 1
            else:
                print(-1)
                break
        print_ans(common_books[:icom] + alice_books[:iali] + bob_books[:ibob] + disliked_books[:idis])
    else:
        for _ in range(m - k):
            if icom and iali < nali and ibob < nbob and get0(alice_books, iali) + get0(bob_books, ibob) - get0(common_books, icom - 1) >= get0(disliked_books, idis):
                icom -= 1
                total -= get0(common_books, icom)
                total += get0(alice_books, icom)
                total += get0(bob_books, ibob)
                iali += 1
                ibob += 1
            elif idis < ndis:
                total += get0(disliked_books, idis)
                idis += 1
        print_ans(common_books[:icom] + alice_books[:iali] + bob_books[:ibob] + disliked_books[:idis])
