#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
vector<pair<int, int> > both, a, b, non;
int n, m, k;
int bothsum[maxn], asum[maxn], bsum[maxn], nonsum[maxn];
int get(vector<pair<int, int> >& V, int x) {
  int l = -1, r = V.size();
  while (l + 1 < r) {
    int mid = l + r >> 1;
    if (V[mid].first <= x)
      l = mid;
    else
      r = mid;
  }
  return l + 1;
}
int main() {
  cin >> n >> m >> k;
  for (int i = 1; i <= n; i++) {
    int t, x, y;
    scanf("%d%d%d", &t, &x, &y);
    if (x == 1 && y == 1)
      both.push_back({t, i});
    else if (x == 1)
      a.push_back({t, i});
    else if (y == 1)
      b.push_back({t, i});
    else
      non.push_back({t, i});
  }
  sort(both.begin(), both.end());
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  sort(non.begin(), non.end());
  for (int i = 1; i <= both.size(); i++)
    bothsum[i] = bothsum[i - 1] + both[i - 1].first;
  for (int i = 1; i <= a.size(); i++) asum[i] = asum[i - 1] + a[i - 1].first;
  for (int i = 1; i <= b.size(); i++) bsum[i] = bsum[i - 1] + b[i - 1].first;
  for (int i = 1; i <= non.size(); i++)
    nonsum[i] = nonsum[i - 1] + non[i - 1].first;
  long long ans = 1e18, BO, A, B, NO;
  for (int i = 0; i <= both.size() && i <= m; i++) {
    int cho = max(k - i, 0);
    if (a.size() < cho || b.size() < cho) continue;
    int x = m - cho * 2 - i, l = 0, r = 1e5;
    if (x < 0) continue;
    while (l + 1 < r) {
      int mid = l + r >> 1;
      int ac = max(get(a, mid) - cho, 0), bc = max(get(b, mid) - cho, 0),
          nonc = get(non, mid);
      if (ac + bc + nonc >= x)
        r = mid;
      else
        l = mid;
    }
    int ac = max(get(a, r) - cho, 0), bc = max(get(b, r) - cho, 0),
        nonc = get(non, r);
    if (ac + bc + nonc < x) {
      cout << i << ' ' << both.size() << ' ' << a.size() << ' ' << b.size()
           << ' ' << non.size() << ' ' << cho;
      return 0;
    }
    long long now = bothsum[i] + asum[cho + ac] + bsum[cho + bc] + nonsum[nonc];
    if (ac + bc + nonc > x) now -= (ac + bc + nonc - x) * r;
    if (now < ans) {
      BO = i;
      A = ac;
      B = bc;
      NO = nonc;
      ans = now;
    }
  }
  if (ans == 1e18)
    puts("-1");
  else {
    cout << ans << endl;
    vector<pair<int, int> > V;
    int cho = max(0LL, k - BO);
    for (int i = 0; i < BO; i++) cout << both[i].second << ' ';
    for (int i = 0; i < cho; i++)
      cout << a[i].second << ' ' << b[i].second << ' ';
    for (int i = 0; i < A; i++) V.push_back(a[i + cho]);
    for (int i = 0; i < B; i++) V.push_back(b[i + cho]);
    for (int i = 0; i < NO; i++) V.push_back(non[i]);
    sort(V.begin(), V.end());
    for (int i = 0; i < m - BO - 2 * cho; i++) cout << V[i].second << ' ';
  }
  return 0;
}
