#include <bits/stdc++.h>
using namespace std;
long long n, test, res, x, k, u, v, t, y, z, mn, q, m, ans[200001], m1;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  test = 1;
  while (test--) {
    cin >> n >> m >> k;
    m1 = m;
    res = 0;
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        p[4];
    for (int i = 1; i <= n; i++) {
      cin >> x >> y >> z;
      if (y == 1 && z == 0) p[1].push(make_pair(x, i));
      if (y == 0 && z == 1) p[2].push(make_pair(x, i));
      if (y == 1 && z == 1) p[0].push(make_pair(x, i));
      if (y == 0 && z == 0) p[3].push(make_pair(x, i));
    }
    if (p[0].size() + p[1].size() < k || p[0].size() + p[2].size() < k) {
      cout << -1 << endl;
      continue;
    }
    for (int i = 1; i <= k; i++) {
      if (p[0].size())
        u = p[0].top().first;
      else
        u = 1e9;
      if (p[1].size())
        v = p[1].top().first;
      else
        v = 1e9;
      if (p[2].size())
        t = p[2].top().first;
      else
        t = 1e9;
      if (u <= v + t || m <= 1) {
        res += u;
        ans[m] = p[0].top().second;
        p[0].pop();
        m--;
      } else {
        res += v + t;
        ans[m] = p[1].top().second;
        ans[m - 1] = p[2].top().second;
        p[1].pop();
        p[2].pop();
        m -= 2;
      }
      if (m == 0 && i < n) cout << -1 << endl;
    }
    while (m > 0) {
      if (p[0].size())
        u = p[0].top().first;
      else
        u = 1e9;
      if (p[1].size())
        v = p[1].top().first;
      else
        v = 1e9;
      if (p[2].size())
        t = p[2].top().first;
      else
        t = 1e9;
      if (p[3].size())
        q = p[3].top().first;
      else
        q = 1e9;
      mn = min(u, min(v, min(t, q)));
      if (mn == u) {
        ans[m] = p[0].top().second;
        p[0].pop();
      } else if (mn == v) {
        ans[m] = p[1].top().second;
        p[1].pop();
      } else if (mn == t) {
        ans[m] = p[2].top().second;
        p[2].pop();
      } else {
        ans[m] = p[3].top().second;
        p[3].pop();
      }
      res += mn;
      m--;
    }
    cout << res << endl;
    for (int i = 1; i <= m1; i++) cout << ans[i] << " ";
  }
}
