#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds; 
using namespace std;
#define lli long long int
#define double long double
#define all(x) x.begin(),x.end()
#define siz(x) x.size()
#define prs(x,y) x.find(y)!=x.end()
#define DEBUG(x) cout << '>' << #x << ':' << x << endl;
#define forn(i,n) for(int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<=(b);i++)
#define FORD(i,a,b) for(int i=(a);i>=(b);i--)
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; }
const int INF = 1<<29;
typedef long long ll;
inline int two(int n) { return 1 << n; }
inline int test(int n, int b) { return (n>>b)&1; }
inline void set_bit(int & n, int b) { n |= two(b); }
inline void unset_bit(int & n, int b) { n &= ~two(b); }
inline int last_bit(int n) { return n & (-n); }
inline int ones(int n) { int res = 0; while(n && ++res) n-=n&(-n); return res;}
inline int level(int n){int ans=0;while(n%2==0){n/=2;ans++;}return ans;}
lli pa[200005],pb[200005],ps[200005];
vector<pair<pair<lli,lli> ,pair<lli,lli> > > st;
int main()
{
	lli n,m,k;
	cin>>n>>m>>k;
	for(lli i=0;i<n;i++)
	{
		lli a,b,c;
		cin>>a>>b>>c;
		st.push_back({{a,i+1},{b,c}});
	}
	sort(all(st));
	pa[n]=pb[n]=ps[n]=0;
	for(lli i=(lli)st.size()-1;i>=0;i--)
	{
		lli a=st[i].second.first;
		lli b= st[i].second.second;
		ps[i]=ps[i+1];
		pa[i]=pa[i+1];
		pb[i]=pb[i+1];
		if(a==1 && b==1)
			ps[i]+=1;
		else if(a==1)
			pa[i]+=1;
		else if(b==1)
			pb[i]+=1;
	}
	lli cnt=0;
	lli t=0,curra=0,currb=0;
	vector<lli> vec;
	for(lli i=0;i<n;i++)
	{
		if(cnt==m)
			break;
		lli a=st[i].second.first;
		lli b= st[i].second.second;

		lli ba=max(0LL,k-(curra+ps[i+1]+a));
		lli bb=max(0LL,k-(currb+ps[i+1]+b));
		lli bs = max(0LL,min(ps[i+1],max(k-(curra+a),k-(currb+b))));
		//cout<<curra<<" "<<currb<<" "<<i<<" "<<cnt<<" ";
		//cout<<ba<<" "<<bb<<" "<<bs<<"\n";
		if(cnt+bs+ba+bb+1>m || ba>pa[i+1] || bb>pb[i+1])
			continue;
		cnt++;
		curra+=a;
		currb+=b;
		t+=st[i].first.first;
		vec.push_back(st[i].first.second);
	}
	if(cnt!=m || curra<k || currb<k)
	{cout<<-1;return 0;}
	cout<<t<<"\n";
	for(auto k: vec)
		cout<<k<<" ";
}

