#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long n, m, books;
  cin >> n >> m >> books;
  vector<pair<long long, long long> > a, b, c, bekar;
  for (long long i = 0; i < n; i++) {
    long long t, a1, a2;
    cin >> t >> a1 >> a2;
    if (a1 && a2) {
      c.push_back({t, i + 1});
    } else if (a1) {
      a.push_back({t, i + 1});
    } else if (a2) {
      b.push_back({t, i + 1});
    } else {
      bekar.push_back({t, i + 1});
    }
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  sort(c.begin(), c.end());
  if (!(a.size() + c.size() >= books && b.size() + c.size() >= books)) {
    cout << -1;
    return 0;
  }
  long long time1 = 0;
  long long i = 0, j = 0, k = 0, x = 0;
  long long bk1 = 0, bk2 = 0;
  long long single;
  if (m > 2 * books)
    single = books;
  else
    single = m - books;
  if (a.size() < single || b.size() < single || c.size() < books - single) {
    cout << -1;
    return 0;
  }
  vector<long long> ans;
  while (bk2 < books - single) {
    ans.push_back(c[x].second);
    time1 += c[x].first;
    x++;
    bk2++;
  }
  while (bk1 < single) {
    ans.push_back(a[i].second);
    time1 += a[i].first;
    ans.push_back(b[i].second);
    time1 += b[i].first;
    i++;
    bk1++;
  }
  while (x < c.size()) {
    bekar.push_back(c[x]);
    x++;
  }
  j = i;
  while (i < a.size()) {
    bekar.push_back(a[i]);
    i++;
  }
  while (j < b.size()) {
    bekar.push_back(b[j]);
    j++;
  }
  sort(bekar.begin(), bekar.end());
  i = 0;
  long long cntt = 2 * bk1 + bk2;
  for (i = 0; i < m - cntt; i++) {
    time1 += bekar[i].first;
    ans.push_back(bekar[i].second);
  }
  cout << time1 << endl;
  for (auto x : ans) cout << x << " ";
}
