#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<int, pii> pipii;
typedef pair<pii, int> piipi;
typedef pair<pii, pii> piipii;

#define mp make_pair
#define fi first
#define se second
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define eb emplace_back

int main(){
    int n, m, k;
    scanf("%d%d%d", &n, &m, &k);

    vector<pii> AB, A, B, C;
    for(int i=1;i<=n;i++){
        int t, a, b;
        scanf("%d%d%d", &t, &a, &b);
        if(a == 1 && b == 1) AB.eb(mp(t, i));
        else if(a == 1) A.eb(mp(t, i));
        else if(b == 1) B.eb(mp(t, i));
        else C.eb(mp(t, i));
    }
    sort(all(AB));
    sort(all(A));
    sort(all(B));
    sort(all(C));

    multiset<int> curA, curB, curF;
    ll sumA = 0, sumB = 0, sumF = 0, sumAB = 0;
    for(int i=0;i<sz(A);i++){
        curA.insert(A[i].fi);
        sumA += A[i].fi;
    }
    for(int i=0;i<sz(B);i++){
        curB.insert(B[i].fi);
        sumB += B[i].fi;
    }
    for(int i=0;i<sz(C);i++){
        curF.insert(C[i].fi);
        sumF += C[i].fi;
    }

    int opt = -1;
    ll ans = 1e18;
    for(int i=0;i<=sz(AB);i++){
        int wA = max(0, k-i), wB = max(0, k-i);
        int wF = m-(i+wA+wB);
        if(wF >= 0){
            while(sz(curA) > wA){
                curF.insert(*curA.rbegin());
                sumF += *curA.rbegin();

                sumA -= *curA.rbegin();
                curA.erase(--curA.end());
            }
            while(sz(curB) > wB){
                curF.insert(*curB.rbegin());
                sumF += *curB.rbegin();

                sumB -= *curB.rbegin();
                curB.erase(--curB.end());
            }
            while(sz(curF) > wF){
                sumF -= *curF.rbegin();
                curF.erase(--curF.end());
            }

            if(sz(curA) == wA && sz(curB) == wB && sz(curF) == wF){
                if(ans > sumAB + sumA + sumB + sumF){
                    ans = sumAB + sumA + sumB + sumF;
                    opt = i;
                }
            }
        }
        if(i == sz(AB)) break;
        sumAB += AB[i].fi;
    }
    if(ans == 1e18) ans = -1;
    printf("%lld\n", ans);
    if(ans != -1){
        vector<int> res;
        int wA = max(0, k-opt), wB = max(0, k-opt);
        for(int i=0;i<opt;i++) res.eb(AB[i].se);
        for(int i=0;i<wA;i++) res.eb(A[i].se);
        for(int i=0;i<wB;i++) res.eb(B[i].se);
        vector<pii> rem;
        for(int i=wA;i<sz(A);i++) rem.eb(A[i]);
        for(int i=wB;i<sz(B);i++) rem.eb(B[i]);
        for(int i=0;i<sz(C);i++) rem.eb(C[i]);
        sort(all(rem));
        for(int i=0;i<m-(opt+wA+wB);i++) res.eb(rem[i].se);
        for(int i=0;i<m;i++) printf("%d ", res[i]);
        printf("\n");
    }
}
	 	  				 		    	    	 	 		