from collections import Counter
n, m, k = map(int, input().split())
dat = [list(map(int, input().split())) for _ in range(n)]
for i, v in enumerate(dat):
    v.append(i)
x = [(v, i, i) for v, a, b, i in dat if a and b]
y = [(v, i) for v, a, b, i in dat if a and not b]
z = [(v, i) for v, a, b, i in dat if not a and b]
x.extend((u + v, i, j) for (u, i), (v, j) in zip(sorted(y), sorted(z)))
if len(x) < k:
    print(-1)
else:
    x.sort()
    xk = x[:k]
    res = sum(v for v, _, _ in xk)
    sk = set()
    for _, i, j in xk:
        sk.update({i, j})
    kk = len(sk)    
    if kk > m:
        x1 = [v for v in x if v[1] == v[2]]
        k1 = sum(1 for v in xk if v[1] == v[2])
        x2 = [v for v in x if v[1] != v[2]]
        k2 = sum(1 for v in xk if v[1] != v[2])
        delta = kk - m
        xk = x1[:k1+delta] + x2[:k2-delta] 
        res = sum(v for v, _, _ in xk)
        sk = set()
        for _, i, j in xk:
            sk.update({i, j})
    elif kk < m:    
        w = sorted((v, i) for v, _, _, i in dat if i not in sk)
        wk = w[:m-kk]
        res += sum(v for v, _ in wk)
        sk.update(i for _, i in wk)
    print(res)
    print(*(v + 1 for v in sk))
         