def g(x):
    if len(x):
        return x[0][0]
    return float('inf')
n,m,k=map(int,input().split())
q,w,e,r=[],[],[],[]
for _ in range(n):
    t,a,b=map(int,input().split())
    if a+b==2:q.append((t,_))
    elif a==1:w.append((t,_))
    elif b==1:e.append((t,_))
    else:r.append((t,_))
q.sort(key=lambda x:x[0])
w.sort(key=lambda x:x[0])
e.sort(key=lambda x:x[0])
r.sort(key=lambda x:x[0])
if len(q)+len(w)<k or len(q)+len(e)<k or len(q)+len(w)+len(e)<m:
    print(-1)
    exit()
ans=0
an=[]
for _ in range(k):
    if len(q):
        if len(w) and len(e):
            if q[0][0]<w[0][0]+e[0][0]:
                asd=q.pop(0)
                ans+=asd[0]
                an.append(asd[1])
            else:
                asd = w.pop(0)
                dsa = e.pop(0)
                ans+=asd[0]+dsa[0]
                an.append(asd[1])
                an.append(dsa[1])
        else:
            asd = q.pop(0)
            ans += asd[0]
            an.append(asd[1])
    else:
        asd = w.pop(0)
        dsa = e.pop(0)
        ans += asd[0] + dsa[0]
        an.append(asd[1])
        an.append(dsa[1])
for _ in range(m-len(an)):
    mn=min(g(q),g(w),g(e),g(r))
    if len(q) and mn == q[0][0]:
        asd=q.pop(0)
        ans += asd[0]
        an.append(asd[1])
    elif len(w) and mn == w[0][0]:
        asd=w.pop(0)
        ans += asd[0]
        an.append(asd[1])
    elif len(e) and mn == e[0][0]:
        asd=e.pop(0)
        ans += asd[0]
        an.append(asd[1])
    else:
        asd=r.pop(0)
        ans += asd[0]
        an.append(asd[1])
print(ans)
for i in an:print(i+1,end=' ')