#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n, k;
  cin >> n >> k;
  vector<long long> alice;
  vector<long long> bob;
  vector<long long> com;
  for (long long i = 0; i < n; i++) {
    long long a1, b1, c1;
    cin >> a1 >> b1 >> c1;
    if (c1 == 1 && b1 == 1) {
      com.push_back(a1);
    } else if (b1 == 1) {
      alice.push_back(a1);
    } else if (c1 == 1) {
      bob.push_back(a1);
    }
  }
  sort(alice.begin(), alice.end());
  sort(bob.begin(), bob.end());
  sort(com.begin(), com.end());
  if (alice.size() + com.size() < k || bob.size() + com.size() < k) {
    cout << -1 << "\n";
    return 0;
  }
  vector<long long> dat;
  if (k <= com.size()) {
    long long cur = 0;
    for (long long i = 0; i < k; i++) {
      cur += com[i];
    }
    dat.push_back(cur);
    for (long long i = 0;
         i < min((long long)alice.size(), (long long)bob.size()); i++) {
      cur -= com[k - 1 - i];
      cur += (alice[i] + bob[i]);
      dat.push_back(cur);
    }
  } else {
    long long cur = 0;
    for (long long i = 0; i < com.size(); i++) {
      cur += com[i];
    }
    long long w = 0;
    for (w = 0; w < k - com.size(); w++) {
      cur += (alice[w] + bob[w]);
    }
    dat.push_back(cur);
    long long pp = 0;
    for (long long j = w;
         j < min((long long)alice.size(), (long long)bob.size()); j++) {
      cur -= com[com.size() - 1 - pp];
      cur += (alice[j] + bob[j]);
      pp++;
      dat.push_back(cur);
    }
  }
  long long asa = dat[0];
  for (long long i = 1; i < dat.size(); i++) {
    if (asa > dat[i]) {
      asa = dat[i];
    }
  }
  cout << asa << "\n";
  return 0;
}
