#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, k;
  scanf("%d", &n), scanf("%d", &m), scanf("%d", &k);
  if (m < k) {
    printf("-1\n");
    return 0;
  }
  vector<pair<int, int> > v, b1, b2, b3;
  vector<int> p;
  long long int sum = 0;
  for (int i = 0, t, a, b; i < n; i++) {
    scanf("%d", &t), scanf("%d", &a), scanf("%d", &b);
    v.push_back(make_pair(t, i));
    if (a == 1 && b == 1)
      b1.push_back(make_pair(t, i));
    else if (a == 1)
      b2.push_back(make_pair(t, i));
    else if (b == 1)
      b3.push_back(make_pair(t, i));
  }
  int l1 = b1.size();
  int l2 = b2.size();
  int l3 = b3.size();
  if (l1) sort(b1.begin(), b1.end());
  if (l2 > 0 && l3 > 0) {
    sort(b2.begin(), b2.end());
    sort(b3.begin(), b3.end());
  }
  int l = min(l2, l3);
  if (l + l1 < k) {
    printf("-1\n");
    return 0;
  }
  int i, x = 0, y = 0;
  for (i = 0; i < k; i++) {
    if (b1[x].first < (b2[y].first + b3[y].first)) {
      sum += 1LL * b1[x].first;
      p.push_back(b1[x].second);
      v.erase(find(v.begin(), v.end(), b1[x]));
      x++;
    } else {
      sum += 1LL * (b2[y].first + b3[y].first);
      p.push_back(b2[y].second);
      p.push_back(b3[y].second);
      v.erase(find(v.begin(), v.end(), b2[y]));
      v.erase(find(v.begin(), v.end(), b3[y]));
      y++;
    }
    if (x == l1 || y == l) break;
  }
  if (i < k) {
    if (l < l1) {
      while (i++ < k) {
        sum += 1LL * b1[x].first;
        p.push_back(b1[x].second);
        v.erase(find(v.begin(), v.end(), b1[x]));
        x++;
      }
    } else {
      while (i++ < k) {
        sum += 1LL * (b2[y].first + b3[y].first);
        p.push_back(b2[y].second);
        p.push_back(b3[y].second);
        v.erase(find(v.begin(), v.end(), b2[y]));
        v.erase(find(v.begin(), v.end(), b3[y]));
        y++;
      }
    }
  }
  sort(v.begin(), v.end());
  for (int j = 0; (j + 1) < (m - k); j++) {
    sum += v[j].first;
    p.push_back(v[j].second);
  }
  printf("%d\n", sum);
  for (auto j = p.begin(); j != p.end(); j++) printf("%d ", (*j + 1));
  printf("\n");
  return 0;
}
