#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k;
  cin >> n >> k;
  vector<int> afor;
  vector<int> bfor;
  int q = 0;
  long sum1 = 0;
  for (int i = 0; i < n; i++) {
    int t, a, b;
    cin >> t >> a >> b;
    if (a == 1 && b == 0) afor.push_back(t);
    if (b == 1 && a == 0) bfor.push_back(t);
    if (a == 1 && b == 1) {
      afor.push_back(t);
      bfor.push_back(t);
      sum1 += t;
    }
  }
  sort(afor.begin(), afor.end());
  sort(bfor.begin(), bfor.end());
  if (afor.size() < k || bfor.size() < k)
    cout << "-1" << endl;
  else if (afor.size() == k && bfor.size() > k) {
    long sum = 0;
    sum = accumulate(afor.begin(), afor.begin() + afor.size(), sum);
    cout << sum << endl;
  } else if (bfor.size() == k && afor.size() > k) {
    long sum = 0;
    sum = accumulate(bfor.begin(), bfor.begin() + bfor.size(), sum);
    cout << sum << endl;
  } else {
    long sum = 0;
    int f = 0, g = 0;
    for (int i = 0; i < k; i++) {
      sum += afor[i];
      sum += bfor[i];
    }
    sum -= sum1;
    cout << sum << endl;
  }
}
