#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n, m, k;
  cin >> n >> m >> k;
  m -= k;
  vector<pair<long long, vector<long long>>> s, a, b, c, ans;
  set<long long> ss;
  for (long long i = 0; i < n; i++) {
    long long t, aa, bb;
    cin >> t >> aa >> bb;
    if (aa + bb == 2)
      s.push_back({t, vector<long long>{i + 1}});
    else if (aa)
      a.push_back({t, vector<long long>{i + 1}});
    else if (bb)
      b.push_back({t, vector<long long>{i + 1}});
    c.push_back({t, vector<long long>{i + 1}});
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  long long i = 0, j, cnt = 0, kk = k;
  while (i < a.size() and i < b.size()) {
    s.push_back({a[i].first + b[i].first,
                 vector<long long>{a[i].second[0], b[i].second[0]}});
    i++;
  }
  sort(c.begin(), c.end());
  sort(s.begin(), s.end());
  for (auto i : s) {
    if (kk and i.second.size() == 1) {
      ans.push_back(i);
      cnt += i.first;
      ss.insert(i.second[0]);
      kk--;
    } else if (kk * m and i.second.size()) {
      ans.push_back(i);
      cnt += i.first;
      ss.insert(i.second[0]);
      ss.insert(i.second[1]);
      m--, kk--;
    }
    if (!kk) break;
  }
  for (i = 0, j = 0; i < n and j < m; i++)
    if (ss.find(c[i].second[0]) == ss.end()) {
      cnt += c[i].first;
      ss.insert(c[i].second[0]);
      j++;
    }
  if (ans.size() < k || j < m) {
    cout << -1 << endl;
    return;
  }
  cout << cnt << endl;
  for (long long i : ss) cout << i << ' ';
  cout << endl;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  solve();
  cerr << "[Execution : " << (1.0 * clock()) / CLOCKS_PER_SEC << "s]\n";
  return 0;
}
