#include <bits/stdc++.h>
using std::min;
const int N = 2e5 + 5;
struct book {
  int id, val, a, b;
  book() {}
  book(int val, int a, int b) : val(val), a(a), b(b) {}
  bool operator<(const book &rhs) const { return val < rhs.val; }
};
bool cmp(const book &x, const book &y) {
  if (x.a != y.a) return x.a < y.a;
  if (x.b != y.b) return x.b < y.b;
  if (x.val != y.val) return x.val < y.val;
}
int main() {
  static book bk[N];
  static std::priority_queue<book> heap;
  int n, m, k;
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= n; i++)
    scanf("%d%d%d", &bk[i].val, &bk[i].a, &bk[i].b), bk[i].id = i;
  std::sort(bk + 1, bk + 1 + n, cmp);
  book *b0 = NULL, *b1 = NULL, *b2 = NULL, *b3 = NULL;
  int n0 = 0, n1 = 0, n2 = 0, n3 = 0;
  for (int i = 1; i <= n; i++) {
    if (bk[i].a == 0 && bk[i].b == 0) b0 && (b0 = bk + i), n0++;
    if (bk[i].a == 0 && bk[i].b == 1) b1 && (b1 = bk + i), n1++;
    if (bk[i].a == 1 && bk[i].b == 0) b2 && (b2 = bk + i), n2++;
    if (bk[i].a == 1 && bk[i].b == 1) b3 && (b3 = bk + i), n3++;
  }
  if (b0 == NULL) b0 = bk + 1;
  if (b1 == NULL) b1 = b0 + n0;
  if (b2 == NULL) b2 = b1 + n1;
  if (b3 == NULL) b3 = b2 + n2;
  if (n3 + min(n1, n2) < k || (k - n3) * 2 > m - n3 || n < m)
    return printf("-1\n"), 0;
  int vans = 0, maxs = min(n1, n2);
  if (maxs > k) maxs = k;
  if (maxs > m / 2) maxs = m / 2;
  int min3 = k - maxs;
  int hp = 0;
  for (int i = 0; i < maxs; i++) vans += b1[i].val + b2[i].val;
  for (int i = 0; i < min3; i++) vans += b3[i].val;
  for (int i = 0; i < n0; i++) heap.push(b0[i]), hp += b0[i].val;
  for (int i = maxs; i < n1; i++) heap.push(b1[i]), hp += b1[i].val;
  for (int i = maxs; i < n2; i++) heap.push(b2[i]), hp += b2[i].val;
  while (heap.size() > m - 2 * k + min3) hp -= heap.top().val, heap.pop();
  int ans = vans + hp, cns = min3;
  for (int i = min3, j = maxs - 1; i < n3 && i < m; i++, j--) {
    vans += b3[i].val;
    if (j >= 0) {
      vans -= b1[j].val + b2[j].val;
      heap.push(b1[j]);
      heap.push(b2[j]);
      hp += b1[j].val + b2[j].val;
    }
    hp -= heap.top().val;
    heap.pop();
    if (ans > vans + hp) ans = vans + hp, cns = min3 + 1;
  }
  printf("%d\n", ans);
  static book tmp[N];
  int pp = 0;
  for (int i = 0; i < cns; i++) printf("%d ", b3[i].id);
  for (int i = 0; i < k - cns; i++) printf("%d %d ", b1[i].id, b2[i].id);
  for (int i = k - cns; i < n1; i++) tmp[++pp] = b1[i];
  for (int i = k - cns; i < n2; i++) tmp[++pp] = b2[i];
  for (int i = 0; i < n0; i++) tmp[++pp] = b0[i];
  std::sort(tmp + 1, tmp + 1 + pp);
  for (int i = 1; i <= m - 2 * k + cns; i++) printf("%d ", tmp[i].id);
  return 0;
}
