#include <bits/stdc++.h>
using namespace std;
const long long int inf = 1000000000;
const long long int MOD = 1000000007;
int main(void) {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  register long long int i, j, k, x, y, m, n, t, q, temp, sum = 0, count = 0,
                                                          f = 1;
  cin >> n >> k;
  vector<long long int> both;
  vector<long long int> a1, b1;
  for (i = 0; i < n; i++) {
    cin >> t >> x >> y;
    if (x == y && x == 1) {
      both.push_back(t);
    } else if (x == 1) {
      a1.push_back(t);
    } else {
      b1.push_back(t);
    }
  }
  sort(a1.begin(), a1.end());
  sort(b1.begin(), b1.end());
  long long int n1 = min(a1.size(), b1.size());
  for (i = 0; i < n1; i++) {
    both.push_back(a1[i] + b1[i]);
  }
  sort(both.begin(), both.end());
  if (both.size() < k)
    cout << "-1";
  else {
    for (i = 0; i < both.size(); i++) sum += both[i];
    cout << sum;
  }
}
