#include <bits/stdc++.h>
const long long N = 1 << 22;
using namespace std;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long lcm(long long a, long long b) { return a * b / gcd(a, b); }
template <class T>
T MIN(const T& a, const T& b) {
  return a < b ? a : b;
}
template <class T>
T MAX(const T& a, const T& b) {
  return a > b ? a : b;
}
long long bit[N + 1];
void update(long long pos, long long val) {
  while (pos <= N) {
    bit[pos] += val;
    pos += pos & (-pos);
  }
}
long long bsearch(long long x) {
  if (x == 0) return 0;
  long long pos = 0;
  for (long long i = N / 2; i >= 1; i >>= 1) {
    if (bit[i + pos] < x) {
      x -= bit[i + pos];
      pos += i;
    }
  }
  return pos + 1;
}
long long getsum(long long pos) {
  long long sum = 0;
  while (pos > 0) {
    sum += bit[pos];
    pos -= pos & (-pos);
  }
  return sum;
}
signed main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  long long n, m, k;
  cin >> n >> m >> k;
  vector<vector<long long>> vec;
  for (long long i = 0; i < n; i++) {
    long long t, a, b;
    cin >> t >> a >> b;
    vec.push_back({t, a, b, i + 1});
  }
  sort(vec.begin(), vec.end());
  long long a = 0, b = 0;
  long long ans = 0, cnt = 0;
  vector<pair<long long, long long>> aa;
  vector<pair<long long, long long>> bb;
  vector<pair<long long, long long>> cc;
  set<long long> book;
  for (auto v : vec) {
    if (!v[1] && b >= k) continue;
    if (!v[2] && a >= k) continue;
    if (!v[1] && !v[2])
      cc.push_back({v[0], v[3]});
    else if (!v[1])
      bb.push_back({v[0], v[3]});
    else if (!v[2])
      aa.push_back({v[0], v[3]});
    else if (a >= k && b >= k && cnt > m) {
      if (aa.size() && bb.size()) {
        ans -= aa.back().first + bb.back().first - v[0];
        book.erase(aa.back().second);
        book.erase(bb.back().second);
        book.insert(v[3]);
        aa.pop_back();
        bb.pop_back();
        cnt--;
      }
      continue;
    }
    if (a >= k && b >= k && cnt == m) break;
    cnt++;
    a += v[1];
    b += v[2];
    ans += v[0];
    book.insert(v[3]);
  }
  while (cnt > m && a - k >= 0 && b - k >= 0) {
    long long x = -1, y = -1, z = -1;
    if (aa.size() && a - k > 0) x = aa.back().first;
    if (bb.size() && b - k > 0) y = bb.back().first;
    if (cc.size()) z = cc.back().first;
    if (x == -1 && y == -1 && z == -1) break;
    if (x >= y && x >= z) {
      a--;
      ans -= aa.back().first;
      book.erase(aa.back().second);
      aa.pop_back();
      cnt--;
    } else if (y >= x && y >= z) {
      b--;
      ans -= bb.back().first;
      book.erase(bb.back().second);
      bb.pop_back();
      cnt--;
    } else {
      ans -= cc.back().first;
      book.erase(cc.back().second);
      cc.pop_back();
      cnt--;
    }
  }
  if (a < k || b < k || cnt != m)
    cout << -1 << endl;
  else {
    cout << ans << endl;
    for (long long t : book) {
      cout << t << " ";
    }
    cout << endl;
  }
  return 0;
}
