#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n, k, t, ans = 0;
  bool a, b;
  cin >> n >> k;
  set<long long> A;
  set<long long> B;
  set<long long> C;
  for (int i = 0; i < n; i++) {
    cin >> t >> a >> b;
    if (a && b) {
      C.insert(t);
    } else if (a) {
      A.insert(t);
    } else if (b) {
      B.insert(t);
    }
  }
  int s1 = A.size(), s2 = B.size(), S = C.size();
  if (S + s1 < k || S + s2 < k) {
    ans = -1;
  } else {
    auto it1 = A.begin();
    auto it2 = B.begin();
    auto it = C.begin();
    int rem = k;
    while (it1 != A.end() && it2 != B.end() && it != C.end() && rem) {
      if (*it1 + *it2 <= *it) {
        ans += *it1 + *it2;
        it1++;
        it2++;
      } else {
        ans += *it;
        it++;
      }
      rem--;
    }
    while (rem) {
      if (it != C.end()) {
        ans += *it;
        it++;
      } else {
        ans += *it1 + *it2;
        it1++;
        it2++;
      }
      rem--;
    }
  }
  cout << ans << "\n";
}
