#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve() {
  int n, k;
  scanf("%d %d", &n, &k);
  vector<int> A, B, C;
  for (int i = 0; i < n; ++i) {
    int t, a, b;
    scanf("%d %d %d", &t, &a, &b);
    if (a & b)
      C.emplace_back(t);
    else if (a)
      A.emplace_back(t);
    else
      B.emplace_back(t);
  }
  sort(A.begin(), A.end());
  sort(B.begin(), B.end());
  for (int i = 0; i < min((int)A.size(), (int)B.size()); ++i)
    C.emplace_back(A[i] + B[i]);
  sort(C.begin(), C.end());
  if ((int)C.size() < k) {
    puts("-1");
  } else {
    int time = 0;
    for (int i = 0; i < k; ++i) time += C[i];
    printf("%d\n", time);
  }
}
int main() {
  solve();
  return 0;
}
