#include <bits/stdc++.h>
using namespace std;
const unsigned long long int INF = numeric_limits<long long int>::max();
long long int k, n, A, B, T;
unsigned long long int ab[200000], a[200000], b[200000];
int main() {
  std::ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  ;
  cin >> n >> k;
  int I = 0, J = 0, K = 0;
  for (int i = 0; i < n; i++) {
    cin >> T >> A >> B;
    if (A == 1 && B == 1)
      ab[I] = T, I++;
    else if (A == 1)
      a[J] = T, J++;
    else if (B == 1)
      b[K] = T, K++;
  }
  sort(ab, ab + I);
  sort(b, b + K);
  sort(a, a + J);
  if (J + I < k || K + I < k) {
    cout << -1 << "\n";
    return 0;
  }
  for (int i = 0; i < k; i++) {
    if (i >= J) a[i] = INF;
    a[i + 1] += a[i];
    if (i >= K) b[i] = INF;
    b[i + 1] += b[i];
    if (i >= I) ab[i] = INF;
    ab[i + 1] += ab[i];
  }
  unsigned long long int ans = ab[k - 1], abi = 0;
  for (int i = k - 1; i >= 0; i--) {
    ans = min(ans, abi + a[i] + b[i]);
    abi = ab[k - i - 1];
  }
  cout << ans << "\n";
  return 0;
}
