#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, k;
pair<int, pair<int, int> > a[N];
vector<long long> L, R, Both;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> k;
  for (int i = 1; i <= n; i++) {
    cin >> a[i].first >> a[i].second.first >> a[i].second.second;
    if (a[i].second.first == 1 && a[i].second.second == 0) {
      L.push_back(a[i].first);
    } else if (a[i].second.first == 0 && a[i].second.second == 1) {
      R.push_back(a[i].first);
    } else if (a[i].second.first == 1) {
      Both.push_back(a[i].first);
    }
  }
  if (min(L.size(), R.size()) + Both.size() < k) {
    cout << -1;
    return 0;
  }
  sort(L.begin(), L.end());
  sort(R.begin(), R.end());
  sort(Both.begin(), Both.end());
  int sz = min(L.size(), R.size());
  int rest = k - sz;
  long long ans = 0;
  for (int i = 0; i < sz; i++) {
    ans += L[i];
    ans += R[i];
  }
  while (--rest >= 0) {
    ans += Both[rest];
  }
  int ind = 0;
  for (int i = k - sz; i < Both.size(); i++) {
    if (Both[i] < L[ind] + R[ind]) {
      ans -= L[ind] + R[ind];
      ans += Both[i];
      ind++;
    } else {
      ind++;
      i--;
    }
    if (ind >= sz) break;
  }
  cout << ans;
  return 0;
}
