#include <bits/stdc++.h>
using namespace std;
const long long int N = 1e5 + 5;
void solve() {
  int n, fc, k;
  cin >> n >> fc >> k;
  vector<pair<int, int> > t, ta, tb, tc;
  int p, q, r;
  for (int i = 1; i <= n; i++) {
    cin >> p >> q >> r;
    if (q == 1 && r == 1)
      t.push_back({p, i});
    else if (q == 1)
      ta.push_back({p, i});
    else if (r == 1)
      tb.push_back({p, i});
    else
      tc.push_back({p, i});
  }
  n = t.size();
  int m = min(ta.size(), tb.size());
  int ma = ta.size();
  int mb = tb.size();
  int mc = tc.size();
  if ((n + m) < k) {
    cout << -1 << endl;
    return;
  }
  set<int> s;
  sort(t.begin(), t.end());
  sort(ta.begin(), ta.end());
  sort(tb.begin(), tb.end());
  int i = 0, j = 0;
  long long int ans = 0, cnt = 0, cnt2 = 0;
  while (cnt < k && i < n && j < m) {
    if (t[i].first <= (ta[j].first + tb[j].first)) {
      ans += t[i].first;
      s.insert(t[i].second);
      i++;
      cnt++;
      cnt2++;
    } else {
      if (cnt2 == fc - 1) break;
      ans += (ta[j].first + tb[j].first);
      s.insert(ta[j].second);
      s.insert(tb[j].second);
      j++;
      cnt++;
      cnt2 += 2;
    }
  }
  while (cnt < k && i < n) {
    ans += t[i].first;
    s.insert(t[i].second);
    i++;
    cnt++;
    cnt2++;
  }
  while (cnt < k && j < m && cnt2 < fc - 1) {
    if (cnt2 == fc - 1) break;
    ans += (ta[j].first + tb[j].first);
    s.insert(ta[j].second);
    s.insert(tb[j].second);
    j++;
    cnt++;
    cnt2 += 2;
  }
  if (cnt2 > fc) {
    cout << -1 << endl;
    return;
  }
  for (; i < n; i++) {
    tc.push_back(t[i]);
  }
  for (int ja = j; ja < ma; ja++) {
    tc.push_back(ta[ja]);
  }
  for (int jb = j; jb < mb; jb++) {
    tc.push_back(tb[jb]);
  }
  sort(tc.begin(), tc.end());
  i = 0;
  while (cnt2 < fc) {
    s.insert(tc[i].second);
    ans += tc[i].first;
    i++;
    cnt2++;
  }
  cout << ans << endl;
  for (int ij : s) {
    cout << ij << " ";
  }
  cout << endl;
}
signed main() {
  int t = 1;
  while (t--) {
    solve();
  }
  return 0;
}
