#include <bits/stdc++.h>
using namespace std;
const int N = 200000, INF = 0x7fffffff;
int tt[N], ta[N], tb[N], tc[N], td[N];
int sa[1 + N], sb[1 + N], sc[1 + N], sd[1 + N];
int na, nb, nc, nd;
int ka, kb, kd;
bool wiggle(int k, int m) {
  int d = max(k - ka, 0) + max(k - kb, 0);
  ka = max(ka, k), kb = max(kb, k);
  kd = max(kd - d, 0);
  while (ka < k || kb < k || ka + kb + kd < m) {
    int t_ = INF, t, choice = 0;
    if (ka < na && t_ > (t = tt[ta[ka]])) {
      t_ = t;
      choice = 1;
    }
    if (kb < nb && t_ > (t = tt[tb[kb]])) {
      t_ = t;
      choice = 2;
    }
    if (kd < nd && t_ > (t = tt[td[kd]])) {
      t_ = t;
      choice = 4;
    }
    if (choice == 0) return false;
    if (choice == 1)
      ka++;
    else if (choice == 2)
      kb++;
    else
      kd++;
  }
  return true;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n, m, k;
  cin >> n >> m >> k;
  for (int i = 0; i < n; i++) {
    int t, a, b;
    cin >> t >> a >> b;
    tt[i] = t;
    if (a && !b)
      ta[na++] = i;
    else if (!a && b)
      tb[nb++] = i;
    else if (a && b)
      tc[nc++] = i;
    else
      td[nd++] = i;
  }
  if (nc + min(na, nb) < k || k * 2 - nc > m) {
    cout << "-1\n";
    return 0;
  }
  sort(ta, ta + na, [](int i, int j) { return tt[i] < tt[j]; });
  sort(tb, tb + nb, [](int i, int j) { return tt[i] < tt[j]; });
  sort(tc, tc + nc, [](int i, int j) { return tt[i] < tt[j]; });
  sort(td, td + nd, [](int i, int j) { return tt[i] < tt[j]; });
  for (int i = 0; i < na; i++) sa[i + 1] = sa[i] + tt[ta[i]];
  for (int i = 0; i < nb; i++) sb[i + 1] = sb[i] + tt[tb[i]];
  for (int i = 0; i < nc; i++) sc[i + 1] = sc[i] + tt[tc[i]];
  for (int i = 0; i < nd; i++) sd[i + 1] = sd[i] + tt[td[i]];
  int l = max(max(k - min(na, nb), k * 2 - m), 0);
  int ans = INF, ka_ = 0, kb_ = 0, kc_ = 0, kd_ = 0;
  for (int x = min(nc, m); x >= l; x--)
    if (wiggle(max(k - x, 0), m - x)) {
      int sum = sa[ka] + sb[kb] + sc[x] + sd[kd];
      if (ans > sum) {
        ans = sum;
        ka_ = ka;
        kb_ = kb;
        kc_ = x;
        kd_ = kd;
      }
    }
  cout << ans << '\n';
  for (int i = 0; i < ka_; i++) cout << ta[i] + 1 << ' ';
  for (int i = 0; i < kb_; i++) cout << tb[i] + 1 << ' ';
  for (int i = 0; i < kc_; i++) cout << tc[i] + 1 << ' ';
  for (int i = 0; i < kd_; i++) cout << td[i] + 1 << ' ';
  cout << '\n';
  return 0;
}
