#include <bits/stdc++.h>
using namespace std;
using Book = pair<int, int>;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int n, m, k;
  cin >> n >> m >> k;
  vector<Book> d[4];
  for (int i = 0; i < n; ++i) {
    int t, a, b;
    cin >> t >> a >> b;
    d[a * 2 + b].emplace_back(t, i + 1);
  }
  int s = max(2 * k - m, 0);
  s += max(k - s - (int)min(d[1].size(), d[2].size()), 0);
  if (s > (int)d[3].size()) {
    cout << "-1\n";
    return 0;
  }
  s += max(m - s - (int)(d[0].size() + d[1].size() + d[2].size()), 0);
  m -= s;
  k = max(k - s, 0);
  for (auto& v : d) sort(v.begin(), v.end());
  int sum = 0;
  unordered_set<int> ids;
  for (int i = 0; i < s; ++i) {
    sum += d[3][i].first;
    ids.insert(d[3][i].second);
  }
  priority_queue<Book> taken;
  priority_queue<Book, vector<Book>, greater<Book>> spare;
  for (int t = 0; t < 3; ++t) {
    for (int i = 0; i < (int)d[t].size(); ++i) {
      if (t > 0 && i < k) {
        sum += d[t][i].first;
        ids.insert(d[t][i].second);
        taken.push(d[t][i]);
      } else {
        spare.push(d[t][i]);
      }
    }
  }
  for (int i = 0; i < m - 2 * k; ++i) {
    assert(!spare.empty());
    sum += spare.top().first;
    ids.insert(spare.top().second);
    taken.push(spare.top());
    spare.pop();
  }
  vector<int> q;
  for (int i = 0; i < m && s + i < (int)d[3].size(); ++i) {
    int delta = d[3][s + i].first;
    q.push_back(d[3][s + i].second);
    for (int t = 0; t < 2 && i + t < m; ++t) {
      assert(!taken.empty());
      delta -= taken.top().first;
      q.push_back(-taken.top().second);
      spare.push(taken.top());
      taken.pop();
    }
    if (i + 1 < m) {
      assert(!spare.empty());
      delta += spare.top().first;
      q.push_back(spare.top().second);
      taken.push(spare.top());
      spare.pop();
    }
    if (delta < 0) {
      sum += delta;
      for (int id : q) {
        if (id > 0)
          ids.insert(id);
        else
          ids.erase(-id);
      }
    }
  }
  cout << sum << '\n';
  for (int id : ids) cout << id << ' ';
  cout << '\n';
  return 0;
}
