#include <bits/stdc++.h>
using namespace std;
int xx[] = {0, 0, -1, 1}, yy[] = {-1, 1, 0, 0};
using ll = long long;
using ppi = pair<int, int>;
using ppl = pair<ll, ll>;
vector<int> L, R, M;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int N, K;
  cin >> N >> K;
  for (long long i = (0); i < (N); ++i) {
    int time, l, r;
    cin >> time >> l >> r;
    if (l + r == 2) {
      M.push_back(time);
    } else {
      if (l)
        L.push_back(time);
      else
        R.push_back(time);
    }
  }
  sort(L.begin(), L.end());
  sort(R.begin(), R.end());
  sort(M.begin(), M.end());
  if (((int)(L.size())) + ((int)(M.size())) < K ||
      ((int)(R.size())) + ((int)(M.size())) < K) {
    cout << -1;
  } else {
    ll tt = 0;
    int l = 0, r = 0, m = 0;
    while (K--) {
      if (l < ((int)(L.size())) && r < ((int)(R.size()))) {
        if (m < ((int)(M.size())) && M[m] <= L[l] + R[r]) {
          tt += M[m++];
        } else {
          tt += L[l++];
          tt += R[r++];
        }
      } else {
        tt += M[m++];
      }
    }
    cout << tt;
  }
  return 0;
}
