#include <bits/stdc++.h>
using namespace std;
class Book {
 public:
  int t, a, b, index;
};
void solve() {
  int n, m, k;
  cin >> n >> m >> k;
  vector<Book> arr(n);
  int alice = 0, bob = 0;
  for (int i = 0; i < n; i++) {
    cin >> arr[i].t >> arr[i].a >> arr[i].b;
    arr[i].index = i + 1;
    alice += arr[i].a;
    bob += arr[i].b;
  }
  if (alice < k || bob < k) {
    cout << -1 << '\n';
    return;
  }
  sort((arr).begin(), (arr).end(), [&](Book& A, Book& B) {
    return A.t == B.t ? A.a + A.b > B.a + B.b : A.t < B.t;
  });
  vector<pair<int, int> > A, B;
  int cnt = 0;
  int ans = 0, pos = n;
  alice = k;
  bob = k;
  vector<bool> vis(n, false);
  for (int i = 0; i < n; i++) {
    if (alice <= 0 && bob <= 0) {
      pos = i;
      break;
    }
    if (arr[i].a == 0 && arr[i].b == 0) continue;
    if (alice > 0 && arr[i].a == 1 && arr[i].b == 0) {
      A.push_back({arr[i].t, i});
      ans += arr[i].t;
      alice--;
      vis[i] = true;
      cnt++;
      continue;
    }
    if (bob > 0 && arr[i].b == 1 && arr[i].a == 0) {
      B.push_back({arr[i].t, i});
      ans += arr[i].t;
      bob--;
      vis[i] = true;
      cnt++;
      continue;
    }
    if (arr[i].a == 1 && arr[i].b == 1) {
      alice--;
      bob--;
      ans += arr[i].t;
      vis[i] = true;
      cnt++;
      continue;
    }
  }
  int ja = 0, jb = 0;
  reverse((A).begin(), (A).end());
  reverse((B).begin(), (B).end());
  while (ja < (int)A.size() && alice < 0) {
    ans -= A[ja].first;
    vis[A[ja].second] = false;
    alice++;
    ja++;
    cnt--;
  }
  while (jb < (int)B.size() && bob < 0) {
    ans -= B[jb].first;
    vis[B[jb].second] = false;
    bob++;
    jb++;
    cnt--;
  }
  for (int i = pos; i < n; i++) {
    if (arr[i].a & arr[i].b) {
      if (ja < (int)A.size() && jb < (int)B.size() &&
          ((A[ja].first + B[jb].first > arr[i].t) || (cnt > m))) {
        ans -= A[ja].first;
        ans -= B[jb].first;
        vis[A[ja].second] = false;
        vis[B[jb].second] = false;
        ans += arr[i].t;
        vis[i] = true;
        cnt--;
        ja++;
        jb++;
      }
    }
  }
  vector<int> res;
  int rem = m - cnt;
  if (rem < 0) {
    cout << -1 << '\n';
    return;
  }
  for (int i = 0; i < n; i++) {
    if (rem == 0) break;
    if (!vis[i]) {
      ans += arr[i].t;
      rem--;
      vis[i] = true;
    }
  }
  for (int i = 0; i < n; i++)
    if (vis[i]) res.push_back(arr[i].index);
  cout << ans << '\n';
  for (int u : res) cout << u << ' ';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  for (int i = 1; i <= t; i++) {
    solve();
  }
  return 0;
}
