#include <bits/stdc++.h>
using namespace std;
vector<string> vec_splitter(string s) {
  s += ',';
  vector<string> res;
  while (!s.empty()) {
    res.push_back(s.substr(0, s.find(',')));
    s = s.substr(s.find(',') + 1);
  }
  return res;
}
void debug_out(vector<string> __attribute__((unused)) args,
               __attribute__((unused)) int idx,
               __attribute__((unused)) int LINE_NUM) {
  cerr << '\n';
}
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
  if (idx > 0)
    cerr << ", ";
  else
    cerr << "Line(" << LINE_NUM << ") ";
  stringstream ss;
  ss << H;
  cerr << args[idx] << " = " << ss.str();
  debug_out(args, idx + 1, LINE_NUM, T...);
}
void run() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr), cout.tie(nullptr);
}
const int mod = 998244353;
long long binpow(long long a, long long b, long long m = mod) {
  a %= m;
  long long res = 1;
  while (b) {
    if (b & 1) res = res * a % m;
    a = a * a % m;
    b >>= 1;
  }
  return res;
}
struct MM {
  int t, a, b;
};
bool cmp(MM a, MM b) {
  if (a.t != b.t) return a.t < b.t;
}
int n, k, m;
int main() {
  run();
  cin >> n >> m >> k;
  multiset<pair<int, int>> a, b, c;
  vector<pair<int, int>> garbage;
  for (int i = 0; i < n; ++i) {
    MM j;
    cin >> j.t >> j.a >> j.b;
    if (j.b == 0 && j.a)
      a.insert({j.t, i + 1});
    else if (j.b && j.a == 0)
      b.insert({j.t, i + 1});
    else if (j.a && j.b) {
      c.insert({j.t, i + 1});
    } else {
      garbage.emplace_back(j.t, i + 1);
    }
  }
  if (((int)((c).size())) + min(((int)((a).size())), ((int)((b).size()))) < k)
    return cout << -1, 0;
  int i = 0;
  long long ans = 0;
  vector<int> idx;
  while (k) {
    auto q1 = a.begin();
    auto q2 = b.begin();
    if (q1 == a.end() || q2 == b.end()) {
      ans += c.begin()->first;
      idx.push_back(c.begin()->second);
      c.erase(c.begin());
      m--;
    } else {
      auto q3 = c.begin();
      if (q3 == c.end()) {
        ans += q1->first + q2->first;
        idx.push_back(q1->second);
        idx.push_back(q2->second);
        a.erase(q1);
        b.erase(q2);
        m -= 2;
      } else if (q1->first + q2->first < q3->first && m - 2 >= k) {
        ans += q1->first + q2->first;
        idx.push_back(q1->second);
        idx.push_back(q2->second);
        a.erase(q1);
        b.erase(q2);
        m -= 2;
      } else {
        idx.push_back(q3->second);
        ans += q3->first;
        c.erase(q3);
        m--;
      }
    }
    k--;
  }
  for (auto x : a) garbage.push_back(x);
  for (auto x : b) garbage.push_back(x);
  for (auto x : c) garbage.push_back(x);
  sort(((garbage).begin()), ((garbage).end()));
  for (int i = 0; i < m; ++i) {
    ans += garbage[i].first;
    idx.push_back(garbage[i].second);
  }
  cout << ans << '\n';
  for (int i : idx) cout << i << ' ';
  return 0;
}
