#include <bits/stdc++.h>
using namespace std;
template <class T>
void printVector(vector<T> const &vec);
int main() {
  int n, m, k;
  cin >> n >> m >> k;
  vector<vector<int> > books(n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < 3; j++) {
      int inputs;
      cin >> inputs;
      books[i].push_back(inputs);
    }
  }
  vector<pair<int, int> > a, b, c, d;
  for (int i = 0; i < n; i++) {
    if (books[i][1] == 1) {
      if (books[i][2] == 1) {
        c.push_back(make_pair(books[i][0], i + 1));
      } else {
        a.push_back(make_pair(books[i][0], i + 1));
      }
    } else if (books[i][2] == 1) {
      b.push_back(make_pair(books[i][0], i + 1));
    } else {
      d.push_back(make_pair(books[i][0], i + 1));
    }
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  sort(c.begin(), c.end());
  sort(d.begin(), d.end());
  if (int(a.size() + c.size()) < k || int(b.size() + c.size()) < k ||
      int(a.size() + b.size() + c.size()) < m || int(c.size()) < 2 * k - m) {
    cout << -1 << endl;
    return 0;
  }
  int minT(0), ka(0), kb(0), kc(0), kd(0);
  vector<int> index;
  while (int(index.size()) < m) {
    if (ka == a.size()) a.push_back(make_pair(987654321, 0));
    if (kb == b.size()) b.push_back(make_pair(987654321, 0));
    if (kc == c.size()) c.push_back(make_pair(987654321, 0));
    if (kd == d.size()) d.push_back(make_pair(987654321, 0));
    if (ka + kc < k && kb + kc < k) {
      if (c[kc].first > a[ka].first + b[kb].first &&
          int(index.size()) + 2 <= m) {
        minT += a[ka].first;
        minT += b[kb].first;
        index.push_back(a[ka].second);
        index.push_back(b[kb].second);
        ka++;
        kb++;
      } else {
        minT += c[kc].first;
        index.push_back(c[kc].second);
        kc++;
      }
    } else {
      if (a[ka].first <= b[kb].first && a[ka].first <= c[kc].first &&
          a[ka].first <= d[kd].first) {
        minT += a[ka].first;
        index.push_back(a[ka].second);
        ka++;
      } else if (b[kb].first <= a[ka].first && b[kb].first <= c[kc].first &&
                 b[kb].first <= d[kd].first) {
        minT += b[kb].first;
        index.push_back(b[kb].second);
        kb++;
      } else if (c[kc].first <= a[ka].first && c[kc].first <= b[kb].first &&
                 c[kc].first <= d[kd].first) {
        minT += c[kc].first;
        index.push_back(c[kc].second);
        kc++;
      } else if (d[kd].first <= a[ka].first && d[kd].first <= b[kb].first &&
                 d[kd].first <= c[kc].first) {
        minT += d[kd].first;
        index.push_back(d[kd].second);
        kd++;
      }
    }
  }
  for (int i = 0; i < m; i++) {
    if (index[i] == 0) {
      cout << -1 << endl;
      return 0;
    }
  }
  cout << minT << endl;
  printVector(index);
  return 0;
}
template <class T>
void printVector(vector<T> const &vec) {
  for (T val : vec) {
    cout << val << " ";
  }
  cout << endl;
}
