#include <bits/stdc++.h>
using namespace std;
void print_vec(vector<pair<int, int> > vec) {
  for (int i = 0; i < vec.size(); ++i) {
    printf("(%d, %d) ", vec[i].first, vec[i].second);
  }
  printf("\n");
}
void print_vec(vector<int> vec) {
  for (int i = 0; i < vec.size(); ++i) {
    printf("%d ", vec[i]);
  }
  printf("\n");
}
int main() {
  long long int n, k, a_like = 0, b_like = 0;
  scanf("%lld %lld", &n, &k);
  vector<int> a_books;
  vector<int> b_books;
  vector<int> both_books;
  for (int i = 0; i < n; i++) {
    int time, a, b;
    scanf("%d %d %d", &time, &a, &b);
    a_like += a;
    b_like += b;
    if (a) {
      a_books.push_back(time);
    }
    if (b) {
      b_books.push_back(time);
    }
    if (a && b) {
      both_books.push_back(time);
    }
  }
  if (a_like < k || b_like < k) {
    printf("-1\n");
    return 0;
  }
  sort(a_books.begin(), a_books.end());
  sort(b_books.begin(), b_books.end());
  sort(both_books.begin(), both_books.end());
  int time_req = 0;
  for (int i = 0; i < k; i++) {
    if (both_books.size() == 0) {
      time_req += a_books[0] + b_books[0];
      a_books.erase(a_books.begin());
      b_books.erase(b_books.begin());
    } else if (a_books[0] + b_books[0] < both_books[0]) {
      time_req += a_books[0] + b_books[0];
      vector<int>::iterator low =
          lower_bound(both_books.begin(), both_books.end(), a_books[0]);
      if (low < both_books.end()) {
        both_books.erase(low);
      }
      low = lower_bound(both_books.begin(), both_books.end(), b_books[0]);
      if (low < both_books.end()) {
        both_books.erase(low);
      }
      a_books.erase(a_books.begin());
      b_books.erase(b_books.begin());
    } else {
      time_req += both_books[0];
      vector<int>::iterator low =
          lower_bound(a_books.begin(), a_books.end(), both_books[0]);
      if (low < a_books.end()) {
        a_books.erase(low);
      }
      low = lower_bound(b_books.begin(), b_books.end(), both_books[0]);
      if (low < b_books.end()) {
        b_books.erase(low);
      }
      both_books.erase(both_books.begin());
    }
  }
  printf("%d\n", time_req);
  return 0;
}
