#define fast ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define It it=se.begin();it!=se.end();it++
#define mem(dp,i) memset(dp,i,sizeof(dp))
#define all(x) begin(x),end(x)
#define unmap unordered_map
#define pii pair<int,int>
#include <bits/stdc++.h>
#define pll pair<ll,ll>
#define vll vector<ll>
#define vi vector<int>
#define ld long double
#define ll long long
#define pb push_back
#define sh short int
#define mid (l+r)/2
#define S second
#define F first
#define sqr 447
using namespace std;
const int inf = 1e9+9;
const int mod = 1e9+7;
const ld pai=acos(-1);
ll n,k,m,ok1,ok2;
ll t[200009];
ll a[200009];
ll b[200009];
vector < ll > v;
vector < pll > v1,v2,v3;
multiset < pll > se;
int main(){
    fast,cin>>n>>m>>k;
    for(int i=0;i<n;i++){
        cin>>t[i]>>a[i]>>b[i];
        ok1 += a[i],ok2 += b[i];
        se.insert({t[i],i});
        if(a[i] && b[i]){
            v3.pb({t[i],i});
            continue;
        }
        if(a[i]) v1.pb({t[i],i});
        if(b[i]) v2.pb({t[i],i});
    }
    if(ok1 < k || ok2 < k){
        cout<<"-1"<<endl;
        return 0;
    }
    sort(all(v1));
    sort(all(v2));
    sort(all(v3));
    ll sz = 0,x = m-k;
    ll i1 = 0,i2 = 0;
    ll i3 = 0,ans = 0;
    while(k--){
        if(i3 < v3.size()){
            if(i1 < v1.size() && i2 < v2.size()){
                if(v1[i1].F+v2[i2].F < v3[i3].F && x > 0){
                    ans += v1[i1].F+v2[i2].F;
                    se.erase(se.find(v1[i1]));
                    se.erase(se.find(v2[i2]));
                v.pb(v1[i1].S),v.pb(v2[i2].S);
                    i1++,i2++,x--,sz += 2;
                }
                else{
                    ans += v3[i3].F;
                    se.erase(se.find(v3[i3]));
                    v.pb(v3[i3].S),i3++,sz++;
                }
            }
            else{
                ans += v3[i3].F;
                se.erase(se.find(v3[i3]));
                v.pb(v3[i3].S),i3++,sz++;
            }
        }
        else if(x <= 0){
            cout<<"-1"<<endl;
            return 0;
        }
        else{
            ans += v1[i1].F+v2[i2].F;
            se.erase(se.find(v1[i1]));
            se.erase(se.find(v2[i2]));
            v.pb(v1[i1].S),v.pb(v2[i2].S);
            i1++,i2++,x--,sz += 2;
        }
    }
    while(sz < m){
        auto it = se.begin();
        ans += it->F,sz++;
        v.pb(it->S);
        se.erase(it);
    }
    cout<<ans<<endl;
    for(auto u:v){
        cout<<u+1<<" ";
    }
    cout<<endl;
}
