#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int MOD = 1e9 + 7;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, m, k;
  cin >> n >> m >> k;
  vector<pair<int, int>> al, bob, both, bad;
  vector<int> ind;
  for (int i = 0; i < n; i++) {
    int t, a, b;
    cin >> t >> a >> b;
    pair<int, int> put = {t, i + 1};
    if (a && b)
      both.push_back(put);
    else if (a)
      al.push_back(put);
    else if (b)
      bob.push_back(put);
    else
      bad.push_back(put);
  }
  sort(both.begin(), both.end());
  sort(al.begin(), al.end());
  sort(bob.begin(), bob.end());
  int resp = 0;
  int count = 0;
  int pal, pbob, pboth;
  pal = pbob = pboth = 0;
  for (int i = 0; i < n && count < k && (k - count < m) && i < m; i++) {
    if (pboth < both.size() && pal < al.size() && pbob < bob.size() &&
        both[pboth].first < al[pal].first + bob[pbob].first) {
      ind.push_back(both[pboth].second);
      resp += both[pboth++].first;
      count++;
      m--;
    } else if (pal < al.size() && pbob < bob.size()) {
      ind.push_back(al[pal].second);
      ind.push_back(bob[pbob].second);
      resp += al[pal++].first + bob[pbob++].first;
      count++;
      m -= 2;
    } else if (pboth < both.size()) {
      ind.push_back(both[pboth].second);
      resp += both[pboth++].first;
      count++;
      m -= 2;
    }
  }
  int i;
  for (i = 0; i < m && count < k && pboth < both.size(); i++) {
    ind.push_back(both[pboth].second);
    resp += both[pboth++].first;
    count++;
  }
  m = m - i;
  int pbad = 0;
  for (i = 0; i < m; i++) {
    int a, b, c, d;
    a = b = c = d = 1e9;
    if (pal < al.size()) a = al[pal].first;
    if (pbob < bob.size()) b = bob[pbob].first;
    if (pboth < both.size()) c = both[pboth].first;
    if (pbad < bad.size()) d = bad[pbad].first;
    if (a == 1e9 && b == 1e9 && c == 1e9) break;
    if (a < b && a < c && a < d) {
      ind.push_back(al[pal].second);
      resp += al[pal++].first;
    } else if (b < a && b < c && b < d) {
      ind.push_back(bob[pbob].second);
      resp += bob[pbob++].first;
    } else if (c < a && c < b && c < d) {
      ind.push_back(both[pboth].second);
      resp += both[pboth++].first;
    } else {
      ind.push_back(bad[pbad].second);
      resp += bad[pbad++].first;
    }
  }
  m = m - i;
  if (count < k || m != 0) {
    resp = -1;
  }
  cout << resp << endl;
  if (resp != -1) {
    for (int i = 0; i < ind.size(); i++) cout << ind[i] << " ";
    cout << endl;
  }
  return 0;
}
