#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, k;
  cin >> n >> k;
  vector<int32_t> a;
  vector<int32_t> b;
  vector<int32_t> ab;
  vector<pair<int, pair<int, int>>> z(n);
  for (int i = 0; i < n; ++i) {
    int tx, ax, bx;
    cin >> tx >> ax >> bx;
    z[i] = {tx, {ax, bx}};
  }
  sort(z.begin(), z.end());
  for (int i = 0; i < n; ++i) {
    int tx = z[i].first;
    int ax = z[i].second.first;
    int bx = z[i].second.second;
    if (ax == bx && ax == 1) {
      ab.push_back(tx);
    } else if (ax == 1 && a.size() < k) {
      a.push_back(tx);
    } else if (bx == 1 && b.size() < k) {
      b.push_back(tx);
    }
  }
  int ia = 0, ib = 0, iab = 0;
  int am = min((int)a.size(), k), bm = min((int)b.size(), k), abm = ab.size();
  int cnta = 0, cntb = 0;
  int ans = 0;
  while (iab < abm && ia < am && ib < bm) {
    if (ab[iab] <= a[ia] + b[ib]) {
      ans += ab[iab];
      iab++;
      am--;
      bm--;
      cnta++;
      cntb++;
    } else {
      ans += a[ia] + b[ib];
      ia++;
      ib++;
      cnta++;
      cntb++;
    }
  }
  if ((a.size() + ab.size() < k) || (b.size() + ab.size()) < k) {
    cout << -1 << '\n';
    return 0;
  }
  while (cnta < k && iab < ab.size()) {
    ans += ab[iab];
    iab++;
    am--;
    bm--;
    cnta++;
    cntb++;
  }
  while (cntb < k && iab < ab.size()) {
    ans += ab[iab];
    iab++;
    am--;
    bm--;
    cnta++;
    cntb++;
  }
  while (cntb < k && ib < b.size()) {
    ans += b[ib];
    ib++;
    cntb++;
  }
  while (cnta < k && ia < a.size()) {
    ans += a[ia];
    ia++;
    cnta++;
  }
  if (cnta >= k && cntb >= k) {
    cout << ans << '\n';
  } else {
    cout << -1 << '\n';
  }
  return 0;
}
