#include <bits/stdc++.h>
using namespace std;
struct point {
  long long t, in;
};
bool ctp(point a, point b) { return a.t <= b.t; }
int32_t main() {
  long long n, k, t, a1, b1, m;
  cin >> n >> m >> k;
  vector<point> c0, c1, c2, c3;
  for (long long i = 0; i < n; i++) {
    cin >> t >> a1 >> b1;
    if (a1 == 1 && b1 == 1)
      c3.push_back({t, i + 1});
    else if (a1 == 1)
      c1.push_back({t, i + 1});
    else if (b1 == 1)
      c2.push_back({t, i + 1});
    else {
      c0.push_back({t, i + 1});
    }
  }
  long long cnta = c1.size();
  long long cntb = c2.size();
  long long cntc = c3.size();
  if (cnta + cntc < k || cntb + cntc < k)
    cout << -1;
  else {
    sort(c1.begin(), c1.end(), ctp);
    sort(c2.begin(), c2.end(), ctp);
    sort(c3.begin(), c3.end(), ctp);
    long long a2 = 0;
    long long b2 = 0;
    long long i = 0;
    long long j = 0;
    long long i1 = 0;
    long long ans = 0;
    vector<long long> ans1;
    long long j1 = 0;
    while (a2 < k && i < cnta && j < cntb && i1 < cntc) {
      if (c1[i].t + c2[j].t < c3[i1].t && j1 < m - 1) {
        ans += c1[i].t + c2[j].t;
        ans1.push_back(c1[i].in);
        ans1.push_back(c2[j].in);
        i++;
        j++;
        j1 += 2;
      } else {
        ans += c3[i1].t;
        ans1.push_back(c3[i1].in);
        i1++;
        j1++;
      }
      a2++;
    }
    if (a2 < k) {
      if (i1 < cntc) {
        while (i1 < cntc && a2 < k) {
          ans += c3[i1].t;
          ans1.push_back(c3[i1].in);
          i1++;
          a2++;
          j1++;
        }
      } else {
        while (a2 < k) {
          ans += c2[j].t + c1[i].t;
          ans1.push_back(c1[i].in);
          ans1.push_back(c2[j].in);
          i++;
          j++;
          a2++;
          j1 += 2;
        }
      }
    }
    if (j1 > m)
      cout << -1;
    else if (j1 == m) {
      cout << ans << endl;
      for (long long i2 = 0; i2 < ans1.size(); i2++) cout << ans1[i2] << " ";
    } else {
      while (i < cnta) {
        c0.push_back(c1[i]);
        i++;
      }
      while (j < cntb) {
        c0.push_back(c2[j]);
        j++;
      }
      while (i1 < cntc) {
        c0.push_back(c3[i1]);
        i1++;
      }
      sort(c0.begin(), c0.end(), ctp);
      i = 0;
      while (j1 < m && i < c0.size()) {
        ans += c0[i].t;
        ans1.push_back(c0[i].in);
        i++;
        j1++;
      }
      if (j1 < m)
        cout << -1;
      else {
        cout << ans << endl;
        for (long long i2 = 0; i2 < ans1.size(); i2++) cout << ans1[i2] << " ";
      }
    }
  }
  return 0;
}
