#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long INFLL = 1e18;
const int MOD = 1000000007;
const int alphabet = 26;
const int MAXINT = 2e5 + 1;
struct book {
  int t, a, b;
};
bool comp(book b1, book b2) {
  if (b1.t != b2.t) return b1.t < b2.t;
  int c1 = b1.a + b1.b, c2 = b2.a + b2.b;
  return c1 > c2;
}
int main() {
  int n, k, ti, a, b, m;
  deque<pair<int, int> > Alice, Bob, Both, rest;
  scanf("%d", &n), scanf("%d", &m), scanf("%d", &k);
  for (int i = 0; i < n; i++) {
    scanf("%d", &ti), scanf("%d", &a), scanf("%d", &b);
    if (a && !b)
      Alice.push_back({ti, i + 1});
    else if (!a && b)
      Bob.push_back({ti, i + 1});
    else if (a && b)
      Both.push_back({ti, i + 1});
    else
      rest.push_back({ti, i + 1});
  }
  sort(Alice.begin(), Alice.end());
  sort(Bob.begin(), Bob.end());
  sort(Both.begin(), Both.end());
  vector<int> tomados;
  int ans = 0;
  while (m > 0 && k && !Both.empty()) {
    if (!Alice.empty() && !Bob.empty() &&
        Alice.front().first + Bob.front().first < Both.front().first &&
        m >= 2) {
      ans += Alice.front().first + Bob.front().first;
      tomados.push_back(Alice.front().second);
      tomados.push_back(Bob.front().second);
      Alice.pop_front();
      Bob.pop_front();
      m -= 2;
    } else {
      ans += Both.front().first;
      tomados.push_back(Both.front().second);
      Both.pop_front();
      m--;
    }
    k--;
  }
  while (m > 0 && k && !Alice.empty() && !Bob.empty()) {
    tomados.push_back(Alice.front().second), ans += Alice.front().first,
        Alice.pop_front();
    tomados.push_back(Bob.front().second), ans += Bob.front().first,
        Bob.pop_front();
    k--, m--, m--;
  }
  if (m > 0) {
    for (pair<int, int> t : Alice) rest.push_back(t);
    for (pair<int, int> t : Bob) rest.push_back(t);
    for (pair<int, int> t : Both) rest.push_back(t);
    sort(rest.begin(), rest.end());
    while (!rest.empty() && m)
      tomados.push_back(rest.front().second), m--, ans += rest.front().first,
          rest.pop_front();
  }
  if (k || m != 0)
    printf("-1\n");
  else {
    printf("%d\n", ans);
    for (int e : tomados) cout << e << " ";
    cout << endl;
  }
}
