#include <bits/stdc++.h>
using namespace std;
void oj() {}
signed main() {
  oj();
  long long n, k, a, b, c;
  cin >> n >> k;
  vector<long long> both, alice, bob;
  for (long long i = 0; i < n; i++) {
    cin >> a >> b >> c;
    if (b & c)
      both.push_back(a);
    else if (b)
      alice.push_back(a);
    else
      bob.push_back(a);
  }
  sort(alice.begin(), alice.end());
  sort(bob.begin(), bob.end());
  if (both.size() + alice.size() < k || both.size() + bob.size() < k) {
    cout << -1;
    return 0;
  }
  for (long long i = 0; i < min(alice.size(), bob.size()); i++)
    both.push_back(alice[i] + bob[i]);
  sort(both.begin(), both.end());
  long long ans = 0;
  for (long long i = 0; i < k; i++) ans += both[i];
  cout << ans << endl;
  return 0;
}
