#include <bits/stdc++.h>
using namespace std;
int n, m, k;
vector<pair<int, int> > both, alice, bob, all;
pair<int, unordered_map<int, bool> > calcUtil(int bothTaken) {
  int satisfy = 0;
  unordered_map<int, bool> taken;
  for (int i = 0; i < bothTaken; i++) {
    satisfy += both[bothTaken - 1].first;
    taken[both[i].second] = 1;
  }
  for (int i = 0; i < k - bothTaken; i++) {
    satisfy += alice[i].first + bob[i].first;
    taken[alice[i].second] = 1;
    taken[bob[i].second] = 1;
  }
  int rest = m - (2 * k - bothTaken);
  for (int i = 0; i < n && rest > 0; i++) {
    if (!taken[all[i].second]) {
      satisfy += all[i].first;
      taken[all[i].second] = 1;
      rest--;
    }
  }
  return {satisfy, taken};
}
int calc(int bothTaken) { return calcUtil(bothTaken).first; }
void printAns(int bothTaken) {
  auto ans = calcUtil(bothTaken);
  cout << ans.first << endl;
  for (int i = 0; i < n; i++) {
    if (ans.second[i]) cout << i + 1 << " ";
  }
  cout << endl;
}
int main() {
  cin >> n >> m >> k;
  for (int i = 0; i < n; i++) {
    int t, a, b;
    cin >> t >> a >> b;
    auto val = make_pair(t, i);
    if (a && b)
      both.push_back(val);
    else if (a)
      alice.push_back(val);
    else if (b)
      bob.push_back(val);
    all.push_back(val);
  }
  sort(both.begin(), both.end());
  sort(alice.begin(), alice.end());
  sort(bob.begin(), bob.end());
  sort(all.begin(), all.end());
  int lo = max(0, max(2 * k - m, k - (int)min(alice.size(), bob.size())));
  int hi = min((int)both.size(), m);
  if (lo > hi) {
    cout << -1 << endl;
    return 0;
  }
  pair<int, int> mn = {calc(lo), lo};
  while (lo < hi) {
    int mid = (lo + hi) / 2;
    int f1 = calc(mid);
    int f2 = calc(mid + 1);
    if (f1 > f2) {
      lo = mid + 1;
      mn = min(mn, {f2, mid + 1});
    } else {
      hi = mid;
      mn = min(mn, {f1, mid});
    }
  }
  printAns(mn.second);
  return 0;
}
