#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
int n, m, k, tot, tmp[4];
struct node {
  int no, t;
  bool operator<(const node &rhs) const { return t > rhs.t; }
};
priority_queue<node> book[4], ans[4];
void switchD(int v) {
  node x = book[v].top();
  tot += x.t, x.t = -x.t;
  ans[v].push(x), book[v].pop(), --m;
}
void switchR(int v) {
  node x = ans[v].top();
  tot += x.t, x.t = -x.t;
  book[v].push(x), ans[v].pop(), ++m;
}
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1, t, a, b; i <= n; ++i)
    scanf("%d%d%d", &t, &a, &b), book[a << 1 | b].push({i, t});
  while (k--) {
    for (int i = 1; i < 4; ++i) tmp[i] = !book[i].empty();
    if ((tmp[1] + tmp[2] < 2) && tmp[3])
      switchD(3);
    else if ((!tmp[3]) && tmp[1] && tmp[2])
      switchD(1), switchD(2);
    else if (tmp[3] + tmp[2] + tmp[1] == 3)
      (book[1].top().t + book[2].top().t > book[3].top().t) ? switchD(3)
                                                            : switchD(1),
          switchD(2);
    else {
      puts("-1");
      return 0;
    }
  }
  while (m < 0) {
    tmp[1] = !ans[1].empty(), tmp[2] = !ans[2].empty(),
    tmp[3] = !book[3].empty();
    if (tmp[1] && tmp[2] && tmp[3])
      switchR(1), switchR(2), switchD(3);
    else {
      puts("-1");
      return 0;
    }
  }
  while (m > 0) {
    int now = -1, v = 1e9;
    for (int i = 0; i < 4; ++i)
      if ((!book[i].empty()) && v > book[i].top().t)
        now = i, v = book[i].top().t;
    if (now == -1) {
      puts("-1");
      return 0;
    } else
      switchD(now);
  }
  printf("%d\n", tot);
  for (int i = 0; i < 4; ++i)
    while (!ans[i].empty()) printf("%d ", ans[i].top().no), ans[i].pop();
  return 0;
}
