#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long MN = 2e6 + 10;
long long A[MN];
int main() {
  srand(time(0));
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  long long N, M, K;
  cin >> N >> M >> K;
  deque<pair<int, int> > A, B, C, D;
  for (int i = 1; i <= N; i++) {
    int t, x, y;
    cin >> t >> x >> y;
    if (x + y == 2) {
      C.push_back(pair<int, int>(t, i));
    } else if (x == 1) {
      A.push_back(pair<int, int>(t, i));
    } else if (y == 1) {
      B.push_back(pair<int, int>(t, i));
    } else {
      D.push_back(pair<int, int>(t, i));
    }
  }
  sort(A.begin(), A.end());
  A.push_back(pair<int, int>(mod, -1));
  sort(B.begin(), B.end());
  B.push_back(pair<int, int>(mod, -1));
  sort(C.begin(), C.end());
  C.push_back(pair<int, int>(mod, -1));
  sort(D.begin(), D.end());
  D.push_back(pair<int, int>(mod, -1));
  if (C.size() + min(A.size(), B.size()) < K) {
    cout << -1 << "\n";
    return 0;
  }
  long long sol = 0;
  vector<int> vsol;
  while (M) {
    if (!K) {
      deque<pair<int, int> > *ptr = &A;
      if (B.front() < ptr->front()) ptr = &B;
      if (C.front() < ptr->front()) ptr = &C;
      if (D.front() < ptr->front()) ptr = &D;
      sol += ptr->front().first;
      vsol.push_back(ptr->front().second);
    } else if (M < K) {
      sol = -1;
      break;
    } else if (M == K) {
      if (C.size() == 0) {
        sol = -1;
        break;
      } else {
        sol += C.front().first;
        vsol.push_back(C.front().second);
        K--;
      }
    } else {
      if (C.size() > 0 && A.size() > 0 && B.size() > 0) {
        if (C.front().first < A.front().first + B.front().first) {
          sol += C.front().first;
          vsol.push_back(C.front().second);
          C.pop_front();
          K--;
        } else {
          sol += A.front().first + B.front().first;
          vsol.push_back(A.front().second);
          vsol.push_back(B.front().second);
          A.pop_front();
          B.pop_front();
          K--;
          M--;
        }
      } else if (C.size() > 0) {
        sol += C.front().first;
        vsol.push_back(C.front().second);
        C.pop_front();
        K--;
      } else if (A.size() > 0 && B.size() > 0) {
        sol += A.front().first + B.front().first;
        vsol.push_back(A.front().second);
        vsol.push_back(B.front().second);
        A.pop_front();
        B.pop_front();
        K--;
        M--;
      } else {
        sol = -1;
        break;
      }
    }
    M--;
  }
  cout << sol << "\n";
  if (sol != -1) {
    for (int i = 0; i < (int)vsol.size(); i++) {
      if (i) cout << " ";
      cout << vsol[i];
    }
  }
  cout << "\n";
  return 0;
}
