#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int mod2 = 998244353;
long long exp(long long taban, long long us, long long md) {
  long long carpan = taban % md;
  if (carpan == 0) return 0;
  long long temp = us;
  long long res = 1;
  while (temp) {
    if (temp % 2) res = (res * carpan) % md;
    temp /= 2;
    carpan = (carpan * carpan) % md;
  }
  return res;
}
long long ebob(long long a, long long b) {
  if (!a) return b;
  return ebob(b % a, a);
}
long long ekok(long long a, long long b) { return (a * b) / ebob(a, b); }
vector<long long> fact;
vector<long long> inv_fact;
void fact_init(int n) {
  fact.resize(n + 5);
  inv_fact.resize(n + 5);
  fact[0] = inv_fact[0] = 1;
  for (int i = 1; i <= n; i++) {
    fact[i] = (fact[i - 1] * i) % mod;
    inv_fact[i] = exp(fact[i], mod - 2, mod);
  }
}
long long komb(long long a, long long b) {
  if (a < b) return 0;
  return fact[a] * (inv_fact[a - b] * inv_fact[b] % mod) % mod;
}
const int N = 2e5 + 5;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int n, k;
  cin >> n >> k;
  vector<int> w[3];
  int ac = 0, bc = 0;
  int tot = 0;
  for (int i = 0; i < n; i++) {
    int t, a, b;
    cin >> t >> a >> b;
    if (!a && !b) continue;
    w[2 * b + a - 1].push_back(t);
    ac += a, bc += b;
    tot += t;
  }
  if (ac < k || bc < k) {
    cout << -1;
    return 0;
  }
  int m = w[0].size() + w[1].size() + w[2].size();
  int s0 = w[0].size(), s1 = w[1].size(), s2 = w[2].size();
  sort((w[0]).rbegin(), (w[0]).rend()), sort((w[1]).rbegin(), (w[1]).rend()),
      sort((w[2]).rbegin(), (w[2]).rend());
  int ptr0 = 0, ptr1 = 0, ptr2 = 0;
  while (ac > k || bc > k) {
    if (ptr2 == s2) {
      bool check = 0;
      if (ac > k) {
        tot -= w[0][ptr0++];
        check = 1;
      }
      if (bc > k) {
        tot -= w[1][ptr1++];
        bc--;
        check = 1;
      }
      if (check) continue;
    }
    if (ac > k && bc > k) {
      bool yap = false;
      yap |= ptr0 == s0;
      yap |= ptr1 == s1;
      yap &= ptr2 < s2;
      yap |= (ptr0 < s0 && ptr1 < s1 && ptr2 < s2 &&
              w[0][ptr0] + w[1][ptr1] <= w[2][ptr2]);
      if (yap) {
        tot -= w[2][ptr2++];
        ac--;
        bc--;
        continue;
      }
    }
    if (ac > k) {
      tot -= w[0][ptr0++];
      ac--;
    }
    if (bc > k) {
      tot -= w[1][ptr1++];
      bc--;
    }
  }
  cout << tot;
}
