#include <bits/stdc++.h>
using namespace std;
const int MAX = 2e5 + 10;
const int inf = 0xfffff;
struct Book {
  int pos;
  int t;
  bool operator<(const Book &b) const { return t < b.t; }
};
int n, m, k, anum = 0, bnum = 0, abnum = 0;
vector<Book> book[4], other;
int visited[MAX] = {false};
long long anst = 0;
int cal(int num) {
  other.clear();
  int total = 0, need = max(k - num, 0);
  if (book[1].size() < need || book[2].size() < need) return inf;
  for (int i = 0; i < num; i++) {
    total += book[3][i].t;
  }
  for (int i = 0; i < need; i++) {
    total += book[1][i].t;
  }
  for (int i = 0; i < need; i++) {
    total += book[2][i].t;
  }
  for (int i = need; i < book[1].size(); i++) {
    other.push_back(book[1][i]);
  }
  for (int i = need; i < book[2].size(); i++) {
    other.push_back(book[2][i]);
  }
  for (int i = 0; i < book[0].size(); i++) {
    other.push_back(book[0][i]);
  }
  for (int i = num; i < book[3].size(); i++) {
    other.push_back(book[3][i]);
  }
  sort(other.begin(), other.end());
  for (int i = 0; i < m - (num + 2 * need); i++) {
    total += other[i].t;
  }
  return total;
}
int main() {
  cin >> n >> m >> k;
  for (int i = 0; i < n; i++) {
    int t, al, bo;
    scanf("%d%d%d", &t, &al, &bo);
    if (al) anum++;
    if (bo) bnum++;
    if (al && bo) abnum++;
    book[2 * al + bo].push_back({i + 1, t});
  }
  if (anum < k || bnum < k || abnum < 2 * k - m) {
    printf("-1");
    return 0;
  }
  for (int i = 0; i < 4; i++) sort(book[i].begin(), book[i].end());
  int l = max(0, 2 * k - m), r = min(m, (int)book[3].size());
  while (l < r) {
    int minl = l + (r - l) / 3;
    int minr = r - (r - l) / 3;
    if (cal(minl) < cal(minr))
      r = minr - 1;
    else
      l = minl + 1;
  }
  int num = l, need = max(0, k - num);
  printf("%d\n", cal(num));
  for (int i = 0; i < num; i++) {
    printf("%d ", book[3][i].pos);
  }
  for (int i = 0; i < need; i++) {
    printf("%d ", book[1][i].pos);
  }
  for (int i = 0; i < need; i++) {
    printf("%d ", book[2][i].pos);
  }
  for (int i = 0; i < m - (num + 2 * need); i++) {
    printf("%d ", other[i].pos);
  }
  return 0;
}
