#include <bits/stdc++.h>
using namespace std;
map<long long, vector<long long>> doub;
map<long long, vector<long long>> sing;
int main() {
  long long a = 0, b = 0;
  long long n, k;
  long long ti, al, bl, time = 0;
  cin >> n >> k;
  for (int i = 0; i < n; ++i) {
    cin >> ti >> al >> bl;
    if (al + bl == 2) {
      doub[ti] = {al, bl};
    } else if (al + bl == 1) {
      sing[ti] = {al, bl};
    }
    a += al;
    b += bl;
  }
  if (a < k || b < k) {
    cout << -1 << endl;
    return 0;
  }
  a = b = k;
  for (auto& i : doub) {
    if (a > 0 || b > 0) {
      time += i.first;
      a -= 1;
      b -= 1;
    }
    if (a <= 0 && b <= 0) {
      cout << time << endl;
      return 0;
    }
  }
  if (a > 0 || b > 0) {
    for (auto& i : sing) {
      if (a > 0)
        if (i.second[0] == 1) {
          time += i.first;
          a -= 1;
        }
      if (b > 0)
        if (i.second[1] == 1) {
          time += i.first;
          b -= 1;
        }
      if (a <= 0 && b <= 0) {
        cout << time << endl;
        return 0;
      }
    }
  }
  cout << time << endl;
}
