#include <bits/stdc++.h>
using LL = long long;
using D = double;
using namespace std;
const int N = 2e5 + 1;
int ST[N], ED[N];
LL T[N], sum = 0;
set<pair<LL, int>> S;
LL n, m, k;
void ins(int id, int time) {
  S.insert({T[id], id});
  sum += T[id];
  ST[id] = time;
}
void rem(int id, int time) {
  S.erase({T[id], id});
  if (ED[id] == -1) ED[id] = time;
}
int main() {
  ios::sync_with_stdio(false);
  memset(ST, -1, sizeof(ST));
  memset(ED, -1, sizeof(ED));
  cin >> n >> m >> k;
  vector<LL> v[2][2];
  for (int i = 0; i < n; ++i) {
    LL t, a, b;
    cin >> t >> a >> b;
    T[i] = t;
    v[a][b].push_back(i);
  }
  if (v[1][1].size() + min(v[0][1].size(), v[1][0].size()) < k) {
    cout << -1 << '\n';
    return 0;
  }
  for (int i = 0; i < 2; ++i)
    for (int j = 0; j < 2; ++j)
      sort(v[i][j].begin(), v[i][j].end(),
           [&](LL a, LL b) { return T[a] < T[b]; });
  LL s = 0, sz = min(v[0][1].size(), v[1][0].size());
  LL p = k - min(sz, k);
  while (p < v[1][1].size() && p + (k - p) * 2 > m) p++;
  if (p + (k - p) * 2 > m) {
    cout << -1 << '\n';
    return 0;
  }
  for (int i = 0; i < k - p; ++i) s += T[v[0][1][i]] + T[v[1][0][i]];
  for (int i = 0; i < p; ++i) s += T[v[1][1][i]];
  for (int id : v[0][0]) ins(id, p);
  for (int i = k - p; i < v[0][1].size(); ++i) ins(v[0][1][i], p);
  for (int i = k - p; i < v[1][0].size(); ++i) ins(v[1][0][i], p);
  for (int i = p; i < v[1][1].size(); ++i) ins(v[1][1][i], p);
  while (S.size() > max(0LL, m - (p + (k - p) * 2))) {
    auto it = S.end();
    it--;
    ED[it->second] = p;
    sum -= T[it->second];
    S.erase(it);
  }
  LL res = s + sum, pmn = p;
  while (p < v[1][1].size() && p < k) {
    p++;
    s += T[v[1][1][p - 1]];
    rem(v[1][1][p - 1], p);
    s -= T[v[0][1][k - p]] + T[v[1][0][k - p]];
    ins(v[0][1][k - p], p);
    ins(v[1][0][k - p], p);
    if (s + sum < res) {
      pmn = p;
      res = s + sum;
    }
  }
  cout << res << '\n';
  for (int i = 0; i < pmn; ++i) cout << v[1][1][i] + 1 << ' ';
  for (int i = 0; i < k - pmn; ++i)
    cout << v[0][1][i] + 1 << ' ' << v[1][0][i] + 1 << ' ';
  for (int i = 0; i < n; ++i) {
    if (ST[i] != -1 && ST[i] <= pmn && (ED[i] == -1 || pmn < ED[i]))
      cout << i + 1 << ' ';
  }
}
