#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, m, k;
  cin >> n >> m >> k;
  vector<pair<int, int>> t[4];
  vector<int> T(n), type(n);
  for (int i = 0; i < n; ++i) {
    int x, a, b;
    cin >> x >> a >> b;
    if (a && b)
      t[2].push_back({x, i}), type[i] = 2;
    else if (a)
      t[0].push_back({x, i}), type[i] = 0;
    else if (b)
      t[1].push_back({x, i}), type[i] = 1;
    else
      t[3].push_back({x, i}), type[i] = 3;
    T[i] = x;
  }
  if (t[2].size() + min(t[0].size(), t[1].size()) < k) {
    cout << "-1\n";
    return 0;
  }
  int X = t[2].size();
  if (k > X &&
      (t[0].size() < (k - X) || t[1].size() < (k - X) || 2 * (k - X) > m - X)) {
    cout << "-1\n";
    return 0;
  }
  for (int i = 0; i < 4; ++i) sort(t[i].rbegin(), t[i].rend());
  int ans = 0;
  vector<int> ind;
  while (k--) {
    if (t[0].size() == 0 || t[1].size() == 0 ||
        (t[0].size() && t[1].size() &&
         t[2].back().first < t[0].back().first + t[1].back().first)) {
      ans += t[2].back().first;
      ind.push_back(t[2].back().second);
      t[2].pop_back();
    } else {
      ans += t[0].back().first + t[1].back().first;
      ind.push_back(t[0].back().second);
      ind.push_back(t[1].back().second);
      t[0].pop_back();
      t[1].pop_back();
    }
  }
  while (ind.size() < m) {
    int mn = 1000000000, I = -1;
    for (int i = 0; i < 4; ++i)
      if (t[i].size())
        if (t[i].back().first < mn) mn = t[i].back().first, I = i;
    ans += mn;
    ind.push_back(t[I].back().second);
    t[I].pop_back();
  }
  if (ind.size() > m) {
    vector<int> fin;
    int extra = ind.size() - m;
    while (ind.size()) {
      if (extra && type[ind.back()] != 2) {
        extra -= 1;
        ans -= T[ind.back()];
        ind.pop_back();
        ans -= T[ind.back()];
        ind.pop_back();
        ans += t[2].back().first;
        ind.push_back(t[2].back().second);
        t[2].pop_back();
      }
      fin.push_back(ind.back());
      ind.pop_back();
    }
    swap(fin, ind);
  }
  cout << ans << '\n';
  for (int i : ind) cout << i + 1 << ' ';
  cout << '\n';
}
