#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int64_t n, k;
  cin >> n >> k;
  multiset<int64_t> o, a, b;
  for (int64_t i = 0; i < n; ++i) {
    int64_t t, x, y;
    cin >> t >> x >> y;
    if (x and y)
      o.insert(t);
    else if (x)
      a.insert(t);
    else if (y)
      b.insert(t);
  }
  int64_t tot = 0, da = 0, db = 0;
  while (!o.empty() and !a.empty() and !b.empty()) {
    if (da >= k and db >= k) break;
    int64_t x = *o.begin(), y = *a.begin(), z = *b.begin();
    if (x <= min(y, z))
      tot += x, o.erase(o.begin()), da++, db++;
    else if (y <= min(x, z))
      tot += y, a.erase(a.begin()), da++;
    else if (z <= min(y, z))
      tot += z, b.erase(b.begin()), db++;
  }
  while (!o.empty() and (da < k or db < k))
    tot += *o.begin(), o.erase(o.begin()), da++, db++;
  while (!a.empty() and da < k) tot += *a.begin(), a.erase(a.begin()), da++;
  while (!b.empty() and db < k) tot += *b.begin(), b.erase(b.begin()), db++;
  cout << (da < k or db < k ? -1 : tot);
}
