#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  int n, m, k;
  cin >> n >> m >> k;
  int A = k, B = k;
  long long int res = 0;
  vector<int> vec;
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 greater<pair<int, int>>>
      pq;
  priority_queue<pair<pair<int, int>, pair<int, int>>,
                 vector<pair<pair<int, int>, pair<int, int>>>,
                 greater<pair<pair<int, int>, pair<int, int>>>>
      ab1, ab2;
  int dbl = max(0, 2 * k - m);
  for (int i = 0; i < n; i++) {
    int cost, a, b;
    cin >> cost >> a >> b;
    if (a == 0 and b == 0) {
      pq.push(make_pair(cost, i + 1));
    } else {
      if (a and b)
        ab1.push(make_pair(make_pair(cost, i + 1), make_pair(a, b)));
      else
        ab2.push(make_pair(make_pair(cost, i + 1), make_pair(a, b)));
    }
  }
  if (dbl > ab1.size()) {
    printf("-1\n");
    return 0;
  }
  for (int i = 0; i < dbl; i++) {
    res += ab1.top().first.first;
    vec.push_back(ab1.top().first.second);
    ab1.pop();
    A--;
    B--;
  }
  while (ab1.size()) {
    ab2.push(ab1.top());
    ab1.pop();
  }
  while (ab2.size()) {
    bool use = false;
    auto p = ab2.top();
    ab2.pop();
    if (A > 0 and p.second.first) use = true;
    if (B > 0 and p.second.second) use = true;
    if (!use) {
      pq.push(p.first);
    } else {
      if (p.second.first) A = max(A - 1, 0);
      if (p.second.second) B = max(B - 1, 0);
      res += p.first.first;
      vec.push_back(p.first.second);
    }
  }
  if (A > 0 or B > 0) {
    printf("-1\n");
    return 0;
  }
  while (vec.size() < m) {
    res += pq.top().first;
    vec.push_back(pq.top().second);
    pq.pop();
  }
  cout << res << endl;
  for (int i : vec) {
    cout << i << " ";
  }
  cout << endl;
}
