#include <bits/stdc++.h>
using namespace std;
pair<long long, int> av[200001], bv[200001], cv[200001], dv[200001];
int main() {
  int n, k, m;
  scanf("%d %d %d", &n, &m, &k);
  int aa = 0, bb = 0, cc = 0, dd = 0;
  long long as = 0, bs = 0, cs = 0, ds = 0;
  for (int i = 0; i < n; i++) {
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    if (b == 1 && c == 1)
      av[aa++] = {a, i};
    else if (b == 1)
      bs += a, bv[bb++] = {a, i};
    else if (c == 1)
      cs += a, cv[cc++] = {a, i};
    else
      ds += a, dv[dd++] = {a, i};
  }
  sort(av, av + aa);
  sort(bv, bv + bb);
  sort(cv, cv + cc);
  sort(dv, dv + dd);
  int mai = -1, mbi = -1, mci = -1, mdi = -1;
  int bi = bb, ci = cc, di = dd, q;
  long long ans = 1e18, ret;
  for (int i = 0; i <= aa; i++) {
    if (i) as += av[i - 1].first;
    q = max(0, k - i);
    for (int j = 0; j < 3; j++) {
      if (bi < bb) bs += bv[bi++].first;
      if (ci < cc) cs += cv[ci++].first;
      if (di < dd) ds += dv[di++].first;
    }
    if (q > bb || q > cc || (i + 2 * q) > m || i + bb + cc + dd < m) continue;
    while (i + bi + ci + di > m) {
      long long bt = (bi > q ? bv[bi - 1].first : -1e18);
      long long ct = (ci > q ? cv[ci - 1].first : -1e18);
      long long dt = (di > 0 ? dv[di - 1].first : -1e18);
      if (bt >= ct && bt >= dt)
        bs -= bv[--bi].first;
      else if (ct >= bt && ct >= dt)
        cs -= cv[--ci].first;
      else
        ds -= dv[--di].first;
    }
    ret = as + bs + cs + ds;
    if (ans > ret) {
      ans = ret;
      mai = i, mbi = bi, mci = ci, mdi = di;
    }
  }
  if (ans > 1e17) return !printf("-1");
  printf("%lld\n", ans);
  for (int i = 0; i < mai; i++) printf("%d ", av[i].second + 1);
  for (int i = 0; i < mbi; i++) printf("%d ", bv[i].second + 1);
  for (int i = 0; i < mci; i++) printf("%d ", cv[i].second + 1);
  for (int i = 0; i < mdi; i++) printf("%d ", dv[i].second + 1);
}
