#include <bits/stdc++.h>
using namespace std;
long long int power(long long int t, long long int x) {
  long long int ans = 1;
  while (t > 0) {
    if (t % 2 == 1) ans = (ans * x) % 1000000007;
    t = t / 2;
    x = (x * x) % 1000000007;
  }
  return ans;
}
long long int maxSubArraySum(vector<long long int> a, long long int size) {
  long long int max_so_far = 0, max_ending_here = 0;
  for (long long int i = 0; i < size; i++) {
    max_ending_here = max_ending_here + a[i];
    if (max_ending_here < 0)
      max_ending_here = 0;
    else if (max_so_far < max_ending_here)
      max_so_far = max_ending_here;
  }
  return max_so_far;
}
int main() {
  std::ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int n, k;
  cin >> n >> k;
  vector<long long int> v, a, b;
  ;
  for (long int i = 0; i < n; i++) {
    long long int t, p, q;
    cin >> t >> p >> q;
    if (p == 1 && q == 1)
      v.push_back(t);
    else if (p == 1 && q == 0)
      a.push_back(t);
    else if (q == 1 && p == 0)
      b.push_back(t);
  }
  long long int z = (a.size() > b.size() ? b.size() : a.size());
  sort(v.begin(), v.end());
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  if (k > (v.size() + z)) {
    cout << "-1";
    return 0;
  }
  long long int i = 0, j = 0, time = 0;
  while (i < (k > v.size() ? v.size() : k)) {
    time += v[i];
    i++;
  }
  while (j < (k - i > z ? z : k - i)) {
    time += (a[j] + b[j]);
    j++;
  }
  i = v.size() - 1;
  while (j < z) {
    while (i >= 0 && v[i] <= (a[j] + b[j])) i--;
    if (i < 0) break;
    time += (a[j] + b[j] - v[i]);
    i--;
    j++;
  }
  cout << time;
  return 0;
}
