#include <bits/stdc++.h>
using namespace std;
const int MOD = (int)1e9 + 7;
const int MAX = 1e6;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, m, k, p;
  cin >> n >> m >> k;
  long long int tot = INT_MAX, cur = 0, tot_book = 0;
  priority_queue<pair<long long int, int> > A, B, T, MX, Z;
  vector<int> v;
  int req = k;
  for (int i = 1; i <= n; i++) {
    int t, a, b;
    cin >> t >> a >> b;
    if (a && b)
      T.push({t * -1, i});
    else if (a)
      A.push({t * -1, i});
    else if (b)
      B.push({t * -1, i});
    else
      Z.push({t * -1, i});
  }
  while (!T.empty() && req) {
    req--;
    cur += T.top().first * -1;
    int pos = T.top().second;
    MX.push({T.top().first * -1, pos});
    T.pop();
    tot_book++;
  }
  while (!T.empty()) {
    Z.push(T.top());
    T.pop();
  }
  if (req) {
    if (req > A.size() || req > B.size()) {
      cout << "-1" << endl;
      return 0;
    }
    int need = req;
    while (!A.empty() && need) {
      need--;
      cur += A.top().first * -1;
      int pos = A.top().second;
      v.push_back(pos);
      A.pop();
      tot_book++;
    }
    need = req;
    while (!B.empty() && need) {
      need--;
      cur += B.top().first * -1;
      int pos = B.top().second;
      v.push_back(pos);
      B.pop();
      tot_book++;
    }
  }
  if (tot_book > m) {
    cout << "-1" << endl;
    return 0;
  }
  while (!A.empty() && !B.empty() && !MX.empty() && tot_book + 1 <= m) {
    long long int x = A.top().first * -1;
    long long int y = B.top().first * -1;
    long long int z = MX.top().first;
    if ((x + y) <= z) {
      cur -= z;
      cur += x + y;
      v.push_back(A.top().second);
      v.push_back(B.top().second);
      tot_book++;
      Z.push({MX.top().first * -1, MX.top().second});
      A.pop();
      B.pop();
      MX.pop();
    } else
      break;
  }
  while (!A.empty() && !B.empty() && !MX.empty() && !Z.empty() &&
         tot_book + 1 <= m) {
    long long int x = A.top().first * -1;
    long long int y = B.top().first * -1;
    long long int z = MX.top().first;
    long long int xt = Z.top().first * -1;
    long long int dif = (z - (x + y));
    if (dif <= xt) {
      cur -= z;
      cur += x + y;
      v.push_back(A.top().second);
      v.push_back(B.top().second);
      tot_book++;
      Z.push({MX.top().first * -1, MX.top().second});
      A.pop();
      B.pop();
      MX.pop();
    } else
      break;
  }
  while (!MX.empty()) {
    v.push_back(MX.top().second);
    MX.pop();
  }
  while (!A.empty()) {
    Z.push(A.top());
    A.pop();
  }
  while (!B.empty()) {
    Z.push(B.top());
    B.pop();
  }
  while (!Z.empty() && tot_book + 1 <= m) {
    tot_book++;
    v.push_back(Z.top().second);
    cur += Z.top().first * -1;
    Z.pop();
  }
  cout << cur << endl;
  for (auto i : v) cout << i << " ";
  return 0;
}
