#include <bits/stdc++.h>
using namespace std;
long long value(vector<long long> a) {
  long long res = 0;
  while (a.empty()) {
    res *= 10;
    res += (*(a.end() - 1));
    a.pop_back();
  }
  return res;
}
signed main() {
  long long n, m, k;
  cin >> n >> m >> k;
  vector<pair<long long, long long>> c;
  vector<pair<long long, long long>> d;
  vector<pair<long long, long long>> e;
  vector<pair<long long, long long>> f;
  for (long long i = 0; i < n; i++) {
    long long t, a, b;
    cin >> t >> a >> b;
    if (a && b)
      c.push_back({t, i + 1});
    else if (a)
      d.push_back({t, i + 1});
    else if (b)
      e.push_back({t, i + 1});
    else
      f.push_back({t, i + 1});
  }
  set<long long> st;
  if (c.size() + d.size() < k || c.size() + e.size() < k) {
    cout << -1 << endl;
    return 0;
  }
  sort(c.begin(), c.end());
  sort(d.begin(), d.end());
  sort(e.begin(), e.end());
  long long cnt = 0;
  long long p = 0;
  long long q = 0;
  long long w = 0, x = 0, y = 0;
  long long ans = 0;
  while (c.size() - w && d.size() - x && e.size() - y && (p < k || q < k)) {
    if (c[w].first <= d[x].first + e[y].first || cnt + 1 == m) {
      w++;
      p++;
      q++;
      cnt++;
      ans += c[w - 1].first;
      st.insert(c[w - 1].second);
    } else if (c[w].first > d[x].first + e[y].first) {
      st.insert(d[x].second);
      st.insert(e[y].second);
      x++;
      p++;
      q++;
      y++;
      cnt += 2;
      ans += d[x - 1].first + e[y - 1].first;
    }
  }
  if (p < k && c.size() - w == 0) {
    while (c.size() + x < k) {
      st.insert(d[x].second);
      ans += d[x].first;
      x++;
      p++;
      cnt++;
    }
  } else if (p < k && d.size() - x == 0) {
    while (d.size() + w < k) {
      st.insert(c[w].second);
      ans += c[w].first;
      w++;
      p++;
      q++;
      cnt++;
    }
  }
  if (q < k && c.size() - w == 0) {
    while (c.size() + y < k) {
      st.insert(e[y].second);
      ans += e[y].first;
      y++;
      q++;
      cnt++;
    }
  } else if (q < k && e.size() - y == 0) {
    while (e.size() + w < k) {
      st.insert(c[w].second);
      ans += c[w].first;
      w++;
      p++;
      q++;
      cnt++;
    }
  }
  if (cnt > m) {
    cout << -1 << endl;
    return 0;
  }
  set<pair<long long, long long>> pq;
  for (long long i = w; i < c.size(); i++) pq.insert({c[i].first, c[i].second});
  for (long long i = x; i < d.size(); i++) pq.insert({d[i].first, d[i].second});
  for (long long i = y; i < e.size(); i++) pq.insert({e[i].first, e[i].second});
  for (long long i = 0; i < f.size(); i++) pq.insert({f[i].first, f[i].second});
  while (cnt < m) {
    cnt++;
    ans += pq.begin()->first;
    st.insert(pq.begin()->second);
    pq.erase(pq.begin());
  }
  cout << ans << endl;
  for (auto it = st.begin(); it != st.end(); it++) cout << *it << " ";
  return 0;
}
