#include <bits/stdc++.h>
using namespace std;
long long int add(long long int x, long long int y) {
  x += y;
  while (x >= 1000000007) x -= 1000000007;
  while (x < 0) x += 1000000007;
  return x;
}
long long int mul(long long int x, long long int y) {
  return (x * 1ll * y) % 1000000007;
}
long long int binpow(long long int x, long long int y) {
  long long int z = 1;
  while (y) {
    if (y & 1) z = mul(z, x);
    x = mul(x, x);
    y >>= 1;
  }
  return z;
}
long long int inv(long long int x) { return binpow(x, 1000000007 - 2); }
long long int divide(long long int x, long long int y) {
  return mul(x, inv(y));
}
bool comp(pair<int, pair<int, int> > p1, pair<int, pair<int, int> > p2) {
  return p1.first < p2.first;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n, k;
  cin >> n >> k;
  vector<int> al, bo, both;
  for (int i = 0; i < n; i++) {
    int a, b, c;
    cin >> a >> b >> c;
    if (b && c)
      both.push_back(a);
    else if (a)
      al.push_back(a);
    else
      bo.push_back(a);
  }
  sort(al.begin(), al.end());
  sort(bo.begin(), bo.end());
  for (int i = 0; i < min(al.size(), bo.size()); i++)
    both.push_back(al[i] + bo[i]);
  sort(both.begin(), both.end());
  if (both.size() < k)
    cout << -1;
  else {
    long long int ans = 0;
    for (int i = 0; i < k; i++) ans += both[i];
    cout << ans;
  }
  return 0;
}
