#include <bits/stdc++.h>
using namespace std;
int read(int &x) { return scanf("%d", &x); }
int read(int &x, int &y) { return scanf("%d%d", &x, &y); }
int read(int &x, int &y, int &z) { return scanf("%d%d%d", &x, &y, &z); }
int read(long long &x) { return scanf("%lld", &x); }
int read(long long &x, long long &y) { return scanf("%lld%lld", &x, &y); }
int read(double &x) { return scanf("%lf", &x); }
char buff[2000010];
int read(string &s) {
  int r = scanf("%s", buff);
  s = buff;
  return r;
}
using namespace std;
int main() {
  int TC = 1;
  while (TC-- > 0) {
    int N, M, K;
    read(N, M, K);
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        A, B, C, D;
    for (int i = 0; i < N; ++i) {
      int n, a, b;
      read(n, a, b);
      if (a && b)
        C.push(pair<int, int>(n, i));
      else if (a)
        A.push(pair<int, int>(n, i));
      else if (b)
        B.push(pair<int, int>(n, i));
      else
        D.push(pair<int, int>(n, i));
    }
    long long s = 0;
    int d = M - K;
    set<int> chosen;
    for (int i = 0; i < K && s >= 0; ++i) {
      if (A.size() > 0 && B.size() > 0 && C.size() > 0) {
        if (d > 0 && A.top().first + B.top().first <= C.top().first) {
          s += A.top().first + B.top().first;
          chosen.insert(A.top().second);
          chosen.insert(B.top().second);
          A.pop();
          B.pop();
          d--;
        } else {
          s += C.top().first;
          chosen.insert(C.top().second);
          C.pop();
        }
      } else if (C.size() > 0) {
        s += C.top().first;
        chosen.insert(C.top().second);
        C.pop();
      } else if (d > 0 && A.size() > 0 && B.size() > 0) {
        s += A.top().first + B.top().first;
        chosen.insert(A.top().second);
        chosen.insert(B.top().second);
        A.pop();
        B.pop();
        d--;
      } else {
        s = -1;
      }
    }
    while (A.size()) D.push(A.top()), A.pop();
    while (B.size()) D.push(B.top()), B.pop();
    while (C.size()) D.push(C.top()), C.pop();
    while (d > 0) {
      s += D.top().first;
      chosen.insert(D.top().second);
      d--;
      D.pop();
    }
    cout << s << endl;
    if (s >= 0) {
      for (int n : chosen) {
        cout << n + 1 << " ";
      }
      cout << endl;
    }
  }
}
