#include <bits/stdc++.h>
using namespace std;
struct TP {
  TP() {}
};
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, k, a, b, t, aa = 0, bb = 0;
  scanf("%d %d", &n, &k);
  vector<pair<long long int, int>> alice, bob, both;
  for (int i = 0; i < n; i++) {
    scanf("%d %d %d", &t, &a, &b);
    if (a and !b and (int)(alice.size()) < k)
      alice.push_back({t, 1}), aa++;
    else if (b and !a and (int)(bob.size()) < k)
      bob.push_back({t, 2}), bb++;
    else if (a and b)
      both.push_back({t, 3});
  }
  sort(alice.begin(), alice.end());
  sort(bob.begin(), bob.end());
  sort(both.begin(), both.end());
  while ((int)(both.size()) > 0) {
    if (aa < k or bb < k) {
      alice.insert(alice.begin(), {both[0].first, 3});
      aa++;
      bb++;
    } else
      break;
    both.erase(both.begin());
  }
  while ((int)(both.size()) > 0 and (int)(alice.size()) > 0 and
         (int)(bob.size()) > 0) {
    a = (int)(alice.size()) - 1;
    b = (int)(bob.size()) - 1;
    if (alice[a].second == 1 and bob[b].second == 2) {
      if (alice[a].first + bob[b].first > both[0].first) {
        alice.pop_back();
        bob.pop_back();
        alice.insert(alice.begin(), both[0]);
        both.erase(both.begin());
      } else
        break;
    } else
      break;
  }
  while ((int)(alice.size()) > 0 and k < aa) {
    if (alice[(int)(alice.size()) - 1].second == 1) alice.pop_back(), aa--;
  }
  while ((int)(bob.size()) > 0 and k < bb) {
    if (bob[(int)(bob.size()) - 1].second == 2) bob.pop_back(), bb--;
  }
  if (aa < k or bb < k)
    printf("%d", -1);
  else {
    long long int ans = 0;
    for (int i = 0; i < (int)(alice.size()); i++) ans += alice[i].first;
    for (int i = 0; i < (int)(bob.size()); i++) ans += bob[i].first;
    printf("%lld", ans);
  }
  printf("\n");
  return 0;
}
