#include <bits/stdc++.h>
using namespace std;
const int INF = 0x7fffffff;
int main() {
  int n, m, k;
  while (cin >> n >> m >> k) {
    vector<pair<int, int>> v0, v1, v2, v3;
    for (int i = 0; i < n; i++) {
      int t, a, b, x = 0;
      cin >> t >> a >> b;
      if (a & b) {
        v3.push_back(make_pair(t, i + 1));
      } else if (a) {
        v1.push_back(make_pair(t, i + 1));
      } else if (b) {
        v2.push_back(make_pair(t, i + 1));
      } else {
        v0.push_back(make_pair(t, i + 1));
      }
    }
    int s0 = v0.size();
    int s1 = v1.size();
    int s2 = v2.size();
    int s3 = v3.size();
    v0.push_back(make_pair(INF, -1));
    v1.push_back(make_pair(INF, -1));
    v2.push_back(make_pair(INF, -1));
    sort(v0.begin(), v0.end());
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());
    sort(v3.begin(), v3.end());
    int ans = INF;
    vector<int> ansv(m);
    for (int i = 0; i <= k && i <= s3; i++) {
      int rk = k - i;
      int r = m - (i + rk + rk);
      if (s1 < rk || s2 < rk || r < 0) {
        continue;
      }
      int tmp = 0, p0 = 0, p1 = 0, p2 = 0;
      vector<int> tmpv;
      for (int j = 0; j < i; j++) {
        tmp += v3[j].first;
        tmpv.push_back(v3[j].second);
      }
      while (p1 < rk) {
        tmp += v1[p1].first;
        tmpv.push_back(v1[p1++].second);
      }
      while (p2 < rk) {
        tmp += v2[p2].first;
        tmpv.push_back(v2[p2++].second);
      }
      while (r--) {
        int x = min(v0[p0].first, min(v1[p1].first, v2[p2].first));
        if (x == v0[p0].first) {
          tmp += v0[p0].first;
          tmpv.push_back(v0[p0++].second);
        } else if (x == v1[p1].first) {
          tmp += v1[p1].first;
          tmpv.push_back(v1[p1++].second);
        } else {
          tmp += v2[p2].first;
          tmpv.push_back(v2[p2++].second);
        }
      }
      if (ans > tmp) {
        ans = tmp;
        ansv = tmpv;
      }
    }
    if (ans != INF) {
      cout << ans << endl;
      for (int i = 0; i < m; i++) {
        cout << ansv[i] << ' ';
      }
      cout << endl;
    } else {
      cout << -1 << endl;
    }
  }
  return 0;
}
