#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, int>> alice, bob, both, none;
vector<int> seq;
int main() {
  long long n, k, i, j, m, p, q, a, b, t, ans, counter, book;
  cin >> n >> m >> k;
  for (i = 0; i < n; i++) {
    cin >> t >> a >> b;
    if (a == 1 and b == 1)
      both.push_back(make_pair(t, i + 1));
    else if (a == 1)
      alice.push_back(make_pair(t, i + 1));
    else if (b == 1)
      bob.push_back(make_pair(t, i + 1));
    else
      none.push_back(make_pair(t, i + 1));
  }
  sort(both.begin(), both.end());
  sort(alice.begin(), alice.end());
  sort(bob.begin(), bob.end());
  i = 0, j = 0, p = 0, q = 0, book = 0, counter = 0, ans = 0;
  while (i < both.size() and j < alice.size() and p < bob.size() and
         q < none.size() and counter < k) {
    if (alice[j].first + bob[p].first <= both[i].first and book + 2 <= m) {
      ans += alice[j].first + bob[p].first;
      seq.push_back(alice[j].second);
      seq.push_back(bob[p].second);
      j++, p++, book += 2, counter++;
    } else if (book + 1 <= m) {
      ans += both[i].first;
      seq.push_back(both[i].second);
      i++, book++, counter++;
    } else
      break;
  }
  while (j < alice.size() and p < bob.size() and counter < k and
         book + 2 <= m) {
    ans += alice[j].first + bob[p].first;
    seq.push_back(alice[j].second);
    seq.push_back(bob[p].second);
    j++, p++, book += 2, counter++;
  }
  while (counter < k and i < both.size() and book + 1 <= m) {
    ans += both[i].first;
    seq.push_back(both[i].second);
    i++, book++, counter++;
  }
  while (i < both.size()) {
    none.push_back(both[i]);
    i++;
  }
  while (j < alice.size()) {
    none.push_back(alice[j]);
    j++;
  }
  while (p < bob.size()) {
    none.push_back(bob[p]);
    p++;
  }
  sort(none.begin(), none.end());
  while (q < none.size() and book + 1 <= m) {
    ans += none[q].first;
    seq.push_back(none[q].second);
    q++, book++;
  }
  if (counter < k or book < m) {
    cout << -1 << endl;
  } else {
    cout << ans << endl;
    for (i = 0; i < seq.size(); i++) {
      cout << seq[i] << " ";
    }
    cout << endl;
  }
  return 0;
}
