#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9 + 1;
int n, m, k, t, a, b, anums = 0, bnums = 0, abnums = 0;
vector<pair<int, int> > ti[4];
vector<pair<int, int> > other;
vector<int> ans;
int cal(int num) {
  int tol = 0;
  int need = max(0, k - num);
  other.clear();
  if (ti[1].size() < need || ti[2].size() < need) return inf;
  for (int i = 0; i < need; i++) tol += ti[1][i].first + ti[2][i].first;
  for (int i = 0; i < num; i++) tol += ti[3][i].first;
  for (int i = 0; i < ti[0].size(); i++) other.push_back(ti[0][i]);
  for (int i = need; i < ti[1].size(); i++) other.push_back(ti[1][i]);
  for (int i = need; i < ti[2].size(); i++) other.push_back(ti[2][i]);
  for (int i = num; i < ti[3].size(); i++) other.push_back(ti[3][i]);
  sort(other.begin(), other.end());
  for (int i = 0; i < m - 2 * need - num; i++) tol += other[i].first;
  return tol;
}
int main() {
  cin >> n >> m >> k;
  for (int i = 1; i <= n; i++) {
    cin >> t >> a >> b;
    anums += a;
    bnums += b;
    abnums += a & b;
    ti[2 * a + b].push_back(make_pair(t, i));
  }
  if (anums < k || bnums < k || 2 * k - abnums > m)
    cout << -1 << '\n';
  else {
    for (int i = 0; i < 4; i++) sort(ti[i].begin(), ti[i].end());
    int l = max(0, 2 * k - m), r = abnums;
    while (l + 6 < r) {
      int m1 = (l + r) / 2;
      int m2 = (m1 + r) / 2;
      if (cal(m1) < cal(m2))
        r = m2;
      else
        l = m1;
    }
    int tol = cal(l), num = l;
    for (int i = l + 1; i <= r; i++) {
      int temp = cal(i);
      if (temp < tol) {
        tol = temp;
        num = i;
      }
    }
    tol = cal(num);
    int need = max(0, k - num);
    for (int i = 0; i < need; i++) {
      ans.push_back(ti[1][i].second);
      ans.push_back(ti[2][i].second);
    }
    for (int i = 0; i < num; i++) ans.push_back(ti[3][i].second);
    for (int i = 0; i < m - 2 * need - num; i++) ans.push_back(other[i].second);
    cout << tol << '\n';
    for (int i = 0; i < ans.size(); i++) cout << ans[i] << " ";
    cout << '\n';
  }
  return 0;
}
