#include <bits/stdc++.h>
using namespace std;
struct Obj {
  long long int time;
  int alice;
  int bob;
};
bool sortByTime(const Obj &lhs, const Obj &rhs) { return lhs.time < rhs.time; }
bool sortByAlice(const Obj &lhs, const Obj &rhs) {
  return lhs.alice > rhs.alice;
}
bool sortByBob(const Obj &lhs, const Obj &rhs) { return lhs.bob > rhs.bob; }
int main() {
  long long int n, k, t, a, b, totala = 0, totalb = 0, tempofinal = 0, adda,
                               addb;
  Obj aux;
  vector<Obj> vetor, vetoraux;
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    cin >> t >> a >> b;
    if (a || b) {
      totala += a;
      totalb += b;
      aux.time = t;
      aux.alice = a;
      aux.bob = b;
      vetor.push_back(aux);
    }
  }
  if (totala < k || totalb < k) {
    cout << -1 << endl;
  } else {
    sort(vetor.begin(), vetor.end(), sortByAlice);
    sort(vetor.begin(), vetor.end(), sortByBob);
    sort(vetor.begin(), vetor.end(), sortByTime);
    adda = 0;
    addb = 0;
    for (int i = 0; i < vetor.size(); i++) {
      if (adda >= k && addb >= k) {
        break;
      } else {
        tempofinal += vetor[i].time;
        vetoraux.push_back(vetor[i]);
        adda += vetor[i].alice;
        addb += vetor[i].bob;
      }
    }
    int i = vetoraux.size() - 1;
    while (adda > k) {
      if (vetoraux[i].alice == 1 && vetoraux[i].bob == 0) {
        adda--;
        tempofinal -= vetoraux[i].time;
      }
      i--;
    }
    i = vetoraux.size() - 1;
    while (addb > k) {
      if (vetoraux[i].bob == 1 && vetoraux[i].alice == 0) {
        addb--;
        tempofinal -= vetoraux[i].time;
      }
      i--;
    }
    cout << tempofinal << endl;
  }
  return 0;
}
