#include <bits/stdc++.h>
using namespace std;
int dx[4] = {0, -1, 0, 1};
int dy[4] = {1, 0, -1, 0};
int XX[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int YY[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int n, m, k;
  cin >> n >> m >> k;
  vector<pair<int, pair<int, int>>> vp;
  for (int i = 1; i <= n; i++) {
    long long int t, a, b;
    cin >> t >> a >> b;
    vp.push_back({t, {a, b}});
  }
  sort(vp.begin(), vp.end());
  int x = 0, y = 0;
  long long int totaltime = 0;
  long long int pos = -1;
  multiset<pair<long long int, long long int>> mst1, mst2, mst12, mst00;
  for (int i = 0; i < vp.size(); i++) {
    long long int t = vp[i].first;
    long long int a = vp[i].second.first;
    long long int b = vp[i].second.second;
    if (a) x++;
    if (b) y++;
    if (a != b) {
      if (a)
        mst1.insert({t, i});
      else
        mst2.insert({t, i});
    } else {
      if (a == 1 && b == 1)
        mst12.insert({t, i});
      else
        mst00.insert({t, i});
    }
  }
  if (x < k || y < k) {
    cout << "-1" << endl;
    return 0;
  }
  long long int ans = 0;
  vector<long long int> v;
  while (1) {
    if (ans >= k) break;
    pair<long long int, long long int> p = {INT_MAX, 0};
    pair<long long int, long long int> q = {INT_MAX, 0};
    pair<long long int, long long int> d = {INT_MAX, 0};
    pair<long long int, long long int> e = {INT_MAX, 0};
    if (mst1.size() >= 1) p = *mst1.begin();
    if (mst2.size() >= 1) q = *mst2.begin();
    if (mst12.size() >= 1) d = *mst12.begin();
    if (mst00.size() >= 1) e = *mst00.begin();
    if (p.first + q.first > d.first) {
      totaltime += d.first;
      mst12.erase(mst12.find(d));
      v.push_back(d.second);
      ans++;
    } else {
      totaltime += p.first;
      totaltime += q.first;
      mst1.erase(mst1.find(p));
      mst2.erase(mst2.find(q));
      v.push_back(p.second);
      v.push_back(q.second);
      ans++;
    }
    if (ans >= k) break;
  }
  if (v.size() < m) {
    while (1) {
      if (v.size() == m) break;
      long long int time[4];
      pair<long long int, long long int> p = {INT_MAX, 0};
      pair<long long int, long long int> q = {INT_MAX, 0};
      pair<long long int, long long int> d = {INT_MAX, 0};
      pair<long long int, long long int> e = {INT_MAX, 0};
      if (mst1.size() >= 1) p = *mst1.begin();
      if (mst2.size() >= 1) q = *mst2.begin();
      if (mst12.size() >= 1) d = *mst12.begin();
      if (mst00.size() >= 1) e = *mst00.begin();
      vector<pair<long long int, long long int>> temp;
      temp.push_back(p);
      temp.push_back(q);
      temp.push_back(d);
      temp.push_back(e);
      sort(temp.begin(), temp.end());
      v.push_back(temp[0].second);
      totaltime += temp[0].first;
      if (v.size() == m) break;
    }
  }
  cout << totaltime << endl;
  for (auto x : v) cout << x + 1 << " ";
  cout << endl;
  return 0;
}
