#include <bits/stdc++.h>
using namespace std;
int solve() {
  int n, k;
  cin >> n >> k;
  vector<int> A;
  vector<int> B;
  vector<int> both;
  for (int i = 0; i < n; i++) {
    int t, isA, isB;
    cin >> t >> isA >> isB;
    if (isA && isB) {
      both.push_back(t);
    } else if (isA) {
      A.push_back(t);
    } else {
      B.push_back(t);
    }
  }
  sort(both.begin(), both.end());
  sort(A.begin(), A.end());
  sort(B.begin(), B.end());
  if (A.size() + both.size() < k || B.size() + both.size() < k) {
    return -1;
  }
  int Atime = 0;
  int Btime = 0;
  int Ctime = 0;
  int a = 0;
  int b = 0;
  int c = 0;
  for (; a < A.size(); a++) {
    if (a == k) break;
    Atime += A[a];
  }
  for (; b < B.size(); b++) {
    if (b == k) break;
    Btime += B[b];
  }
  while (a + c < k) {
    Ctime += both[c];
    c++;
    if (b + c > k) {
      b--;
      Btime -= B[b];
    }
  }
  while (b + c < k) {
    Ctime += both[c];
    c++;
    if (a + c > k) {
      a--;
      Atime -= A[a];
    }
  }
  int ret = Atime + Btime + Ctime;
  while (a > 0 && b > 0 && c < both.size()) {
    Ctime += both[c];
    a--;
    b--;
    Atime -= A[a];
    Btime -= B[b];
    ret = min(ret, Atime + Btime + Ctime);
  }
  return ret;
}
int main() { cout << solve() << endl; }
