#include <bits/stdc++.h>
using namespace std;
const int N = 3 * 1e5 + 10;
const int M = 1e6 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
void solve() {
  int n, k;
  cin >> n >> k;
  vector<int> a, b, both;
  for (long long i = 0; i < n; i++) {
    int t, aa, bb;
    cin >> t >> aa >> bb;
    if (aa && bb)
      both.push_back(t);
    else if (aa)
      a.push_back(t);
    else if (bb)
      b.push_back(t);
  }
  sort(begin(a), end(a));
  sort(begin(b), end(b));
  sort(begin(both), end(both));
  long long ans = 0;
  if (a.size() + both.size() < k || b.size() + both.size() < k)
    cout << -1 << endl;
  else if (a.size() < k && b.size() < k) {
    int a_k = k, b_k = k;
    int gap = max(k - a.size(), k - b.size());
    for (long long i = 0; i < gap; i++) {
      ans += both[i];
      a_k--;
      b_k--;
    }
    if (a_k) {
      for (long long i = 0; i < a_k; i++) ans += a[i];
    }
    if (b_k) {
      for (long long i = 0; i < b_k; i++) ans += b[i];
    }
    cout << ans << endl;
  } else if (a.size() < k) {
    int a_k = k, b_k = k;
    int gap = k - a.size();
    for (long long i = 0; i < gap; i++) {
      ans += both[i];
      a_k--;
      b_k--;
    }
    if (a_k) {
      for (long long i = 0; i < a_k; i++) ans += a[i];
    }
    if (b_k) {
      for (long long i = 0; i < b_k; i++) ans += b[i];
    }
    cout << ans << endl;
  } else if (b.size() < k) {
    int a_k = k, b_k = k;
    int gap = k - b.size();
    for (long long i = 0; i < gap; i++) {
      ans += both[i];
      a_k--;
      b_k--;
    }
    if (a_k) {
      for (long long i = 0; i < a_k; i++) ans += a[i];
    }
    if (b_k) {
      for (long long i = 0; i < b_k; i++) ans += b[i];
    }
    cout << ans << endl;
  } else if (a.size() >= k && b.size() >= k) {
    int a_k = k, b_k = k;
    for (long long i = 0; i < both.size(); i++) {
      if (i >= a.size() || i >= b.size()) break;
      if (both[i] <= (a[i] + b[i])) {
        ans += both[i];
        a_k--;
        b_k--;
      }
    }
    if (a_k)
      for (long long i = 0; i < a_k; i++) ans += a[i];
    if (b_k)
      for (long long i = 0; i < b_k; i++) ans += b[i];
    cout << ans << endl;
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  ;
  solve();
  return 0;
}
