#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll fenwik[1000020];
void update(ll pos, ll val) {
  while (pos < 1000020) {
    fenwik[pos] += val;
    pos += (pos & (-pos));
  }
}
ll get(ll pos) {
  ll ans = 0;
  while (pos > 0) {
    ans += fenwik[pos];
    pos -= (pos & (-pos));
  }
  return ans;
}
ll mod = 1e9 + 7;
ll go(ll base, ll pow) {
  base %= mod;
  if (pow == 0) return 1;
  ll x = go(base, pow / 2);
  x = (x * x) % mod;
  if (pow % 2) x = (base * x) % mod;
  return x;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  cout.setf(ios::fixed);
  cout.precision(20);
  ll n, kk;
  cin >> n >> kk;
  vector<ll> a, b, ab;
  for (ll i = 0; i < n; i++) {
    ll x, y, z;
    cin >> x >> y >> z;
    if (y == 1 && z == 1)
      ab.push_back(x);
    else if (y == 1)
      a.push_back(x);
    else
      b.push_back(x);
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  sort(ab.begin(), ab.end());
  ll i = 0, j = 0, k = 0, lol = 0, ans = 0;
  while (1) {
    bool ok = false;
    if (i < a.size() && i < b.size()) {
      ll lagbe = a[i] + b[i];
      ok = true;
      lol++;
      if (k < ab.size()) {
        if (lagbe < ab[k]) {
          ans += lagbe;
          i++;
        } else {
          ans += ab[k++];
        }
      } else {
        ans += lagbe;
        i++;
      }
    } else {
      if (k < ab.size()) {
        lol++;
        ok = true;
        ans += ab[k++];
      }
    }
    if (lol >= kk || ok == false) break;
  }
  if (lol != kk) ans = -1;
  cout << ans << endl;
  return 0;
}
