#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-10, pi = 3.1415926535898;
const int mod = 1e9 + 7, maxn = 2e5 + 10;
int T, n, m, k, x, y, z, a1, b1, c1, vis[maxn];
char st[maxn];
struct P {
  int x, y, z;
  bool operator<(const P& a) const {
    if (x == a.x) return y < a.y;
    return x < a.x;
  }
} p[maxn], a[maxn], b[maxn], c[maxn];
int main(int argc, char const* argv[]) {
  int cnt = 0, ans = 2 * mod, w;
  scanf("%d %d %d", &n, &m, &k);
  priority_queue<P> q;
  for (int i = 1; i <= n; ++i) {
    scanf("%d %d %d", &x, &y, &z);
    p[i].x = x;
    p[i].z = i;
    if (y and z) {
      p[i].y = 1;
      a[++a1] = p[i];
    } else if (y == 1 and z == 0) {
      p[i].y = 2;
      b[++b1] = p[i];
    } else if (y == 0 and z == 1) {
      p[i].y = 3;
      c[++c1] = p[i];
    } else {
      p[i].y = 4;
      q.push({-x, 4, i});
    }
  }
  if (min(b1, c1) < k - a1 or (k - a1) * 2 > m - a1) {
    printf("-1\n");
    return 0;
  }
  int l = min(min(b1, c1), k), r = k - l;
  sort(a + 1, a + a1 + 1);
  sort(b + 1, b + b1 + 1);
  sort(c + 1, c + c1 + 1);
  for (int i = l + 1; i <= b1; ++i) {
    q.push({-b[i].x, b[i].y, b[i].z});
  }
  for (int i = l + 1; i <= c1; ++i) {
    q.push({-c[i].x, c[i].y, c[i].z});
  }
  while (2 * l + r > m) {
    q.push({-c[l].x, c[l].y, c[l].z});
    q.push({-b[l].x, b[l].y, b[l].z});
    --l;
    ++r;
  }
  for (int i = r + 1; i <= a1; ++i) {
    q.push({-a[i].x, a[i].y, a[i].z});
  }
  for (int i = 1; i <= l; ++i) {
    cnt += b[i].x + c[i].x;
  }
  for (int i = 1; i <= r; ++i) {
    cnt += a[i].x;
  }
  for (int i = m - 2 * l - r; i >= 1; --i) {
    P pp = q.top();
    q.pop();
    vis[pp.z] = 1;
    cnt -= pp.x;
  }
  if (cnt < ans) {
    ans = cnt;
    w = l;
  }
  while (l and r < a1) {
    q.push({-c[l].x, c[l].y, c[l].z});
    q.push({-b[l].x, b[l].y, b[l].z});
    cnt -= c[l].x;
    cnt -= b[l].x;
    if (vis[a[r + 1].z]) {
      cnt -= a[r + 1].x;
      P pp = q.top();
      q.pop();
      vis[pp.z] = 1;
      cnt -= pp.x;
    }
    cnt += a[r + 1].x;
    P pp = q.top();
    q.pop();
    vis[pp.z] = 1;
    cnt -= pp.x;
    --l;
    ++r;
    if (cnt < ans) {
      ans = cnt;
      w = l;
    }
  }
  printf("%d\n", ans);
  memset(vis, 0, sizeof(vis));
  x = w, y = k - w;
  for (int i = 1; i <= x; ++i) {
    printf("%d %d ", b[i].z, c[i].z);
    vis[b[i].z] = vis[c[i].z] = 1;
  }
  for (int i = 1; i <= y; ++i) {
    printf("%d ", a[i].z);
    vis[a[i].z] = 1;
  }
  m -= k + x;
  sort(p + 1, p + n + 1);
  for (int i = 1; i <= n; ++i) {
    if (m == 0) break;
    if (vis[p[i].z]) continue;
    printf("%d ", p[i].z);
    --m;
  }
  return 0;
}
