#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
#define lli long long int
#define fop(i,m,n) for (int i=(m);i<(n);i++)
#define FOP(i,m,n) for (int i=(m)-1;i>=(n);--i)
#define test(x) cout << #x << ' ' << x << endl;
#define printv(a) {\
    for (auto y : a) cout << y << ' ';\
    cout << '\n';\
}
#define eb emplace_back
#define pb push_back
#define mp make_pair 
#define mt make_tuple
#define pii pair<int,int> 
#define pll pair<lli,lli>
#define tiii tuple<int,int,int>
#define all(a) a.begin(), a.end()
#define X first
#define Y second
#define oset tree<pii,null_type,less<pii>,rb_tree_tag,tree_order_statistics_node_update>
auto SEED = chrono::steady_clock::now().time_since_epoch().count();
mt19937 rng(SEED);
const int mod = 1e9 + 7, x = 864197532, N = 501, logN = 20, K = 350;

int main () {
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n, m, k, tmp, a, b;
	cin >> n >> m >> k;
	vector <pii> both, A, B, em;
	fop (i,0,n) {
		cin >> tmp >> a >> b;
		if (a && b) both.eb(tmp, i + 1);
		else if (a) A.eb(tmp, i + 1);
		else if (b) B.eb(tmp, i + 1);
		else em.eb(tmp, i + 1);
	}
	if (both.size() + min(A.size(), B.size()) < k) {
		cout << -1 << endl;
		return 0;
	}
	sort(all(both));
	sort(all(A));
	sort(all(B));
	tmp = min(int(A.size()), int(B.size()));
	A.resize(tmp);
	B.resize(tmp);
	sort(all(em));
	lli ans = 1ll << 60, now1 = -1, now2 = -1, now3 = -1;
	int ans_a = -1, ans_b = -1;
	for (int i = min(int(both.size()), k), j = k - i; i >= 0 && j < tmp; --i, ++j) {
		if (m - i - 2 * j > em.size()) continue;
		if (now1 == -1) {
			now1 = now2 = now3 = 0;
			fop (_,0,i) now1 += both[_].X;
			fop (_,0,j) now2 += A[_].X + B[_].X;
			fop (_,0,m - i - 2 * j) now3 += em[_].X;
		} else {
			/*
			1 0 2
			0 1 1
			*/
			now1 -= both[i].X;
			now2 += A[j - 1].X + B[j - 1].X;
			now3 -= em[m - i - 2 * j].X;
		}
		if (ans > now1 + now2 + now3) {
			ans = now1 + now2 + now3;
			ans_a = i;
			ans_b = j;
		}
	}
	cout << ans << endl;
	fop (i,0,ans_a) cout << both[i].Y << ' ';
	fop (i,0,ans_b) cout << A[i].Y << ' ' << B[i].Y << ' ';
	fop (i,0,m - ans_a - ans_b * 2) cout << em[i].Y << ' ';
	cout << endl;
}