#include <bits/stdc++.h>
using namespace std;
long long n, k;
long long a[200005];
long long b[200005];
long long t[200005];
bool used[200005];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> k;
  long long x = 0;
  long long y = 0;
  vector<pair<long long, long long> > v;
  vector<pair<long long, long long> > p;
  for (long long i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
    used[i] = false;
    if (a[i]) x++;
    if (b[i]) y++;
    if (a[i]) v.push_back({t[i], i});
    if (b[i]) p.push_back({t[i], i});
  }
  sort(v.begin(), v.end());
  sort(p.begin(), p.end());
  if (x < k || y < k) {
    cout << "-1" << endl;
    return 0;
  }
  long long ans = 0;
  long long gol = 0;
  if (x <= y) {
    for (long long i = 0; i < k; i++) {
      long long mp = v[i].second;
      if (b[mp]) {
        used[mp] = true;
        gol++;
      }
      gol++;
      ans += v[i].first;
    }
    for (long long i = 0; i < k; i++) {
      if (!used[p[i].second] && gol < (2 * k)) {
        ans += p[i].first;
        gol++;
      }
    }
    cout << ans << endl;
    return 0;
  }
  for (long long i = 0; i < k; i++) {
    long long mp = p[i].second;
    if (a[mp]) {
      used[mp] = true;
      gol++;
    }
    gol++;
    ans += p[i].first;
  }
  for (long long i = 0; i < k; i++) {
    if (!used[v[i].second] && gol < (2 * k)) {
      ans += v[i].first;
      gol++;
    }
  }
  cout << ans << endl;
  return 0;
}
