#include <bits/stdc++.h>
using namespace std;
bool isPrime(long long n) {
  if (n <= 1) return false;
  if (n <= 3) return true;
  if (n % 2 == 0 || n % 3 == 0) return false;
  for (long long i = 5; i * i <= n; i = i + 6)
    if (n % i == 0 || n % (i + 2) == 0) return false;
  return true;
}
vector<long long> prime;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  srand(static_cast<unsigned>(time(0)));
  long long t = 1;
  while (t--) {
    long long k, n, m;
    cin >> n >> m >> k;
    map<long long, long long> mp;
    long long ans = 0;
    vector<pair<long long, long long>> v;
    vector<pair<long long, long long>> alice;
    vector<pair<long long, long long>> bob;
    vector<pair<long long, long long>> al;
    vector<long long> res;
    for (long long i = 0; i < n; ++i) {
      long long t, a, b;
      cin >> t >> a >> b;
      if (b == 1 && a == 1)
        v.push_back({t, i + 1});
      else if (a == 1 && b == 0)
        alice.push_back({t, i + 1});
      else if (b == 1 && a == 0)
        bob.push_back({t, i + 1});
      al.push_back({t, i + 1});
    }
    sort(v.begin(), v.end());
    sort(alice.begin(), alice.end());
    sort(bob.begin(), bob.end());
    sort(al.begin(), al.end());
    long long c = 0, x = 0, y = 0, z = 0, c1 = 0;
    while (c < k) {
      if ((k - c < m - c1) &&
          (x < alice.size() && y < bob.size() &&
           (v.size() == z ||
            (z < v.size() && alice[x].first + bob[y].first <= (v[z].first))))) {
        ans += alice[x].first + bob[y].first;
        res.push_back(alice[x].second);
        res.push_back(bob[y].second);
        mp[alice[x].second]++;
        mp[bob[y].second]++;
        x++, y++;
        c1 += 2;
      } else if ((z < v.size())) {
        ans += v[z].first;
        res.push_back(v[z].second);
        mp[v[z].second]++;
        z++;
        c1++;
      } else
        break;
      c++;
    }
    for (long long i = 0; i < (long long)al.size(); ++i) {
      if (c1 == m) break;
      if (mp[al[i].second] == 0) {
        ans += al[i].first;
        res.push_back(al[i].second);
        c1++;
      }
    }
    if (c1 == m && c == k) {
      cout << ans << '\n';
      for (long long i = 0; i < (long long)res.size(); ++i)
        cout << res[i] << " ";
    } else
      cout << -1 << '\n';
  }
  return 0;
}
