#include <bits/stdc++.h>
using namespace std;
vector<string> split(const string& s, char c) {
  vector<string> v;
  stringstream ss(s);
  string x;
  while (getline(ss, x, c)) v.emplace_back(x);
  return move(v);
}
template <typename T, typename... Args>
inline string arrStr(T arr, int n) {
  stringstream s;
  s << "[";
  for (int i = 0; i < n - 1; i++) s << arr[i] << ",";
  s << arr[n - 1] << "]";
  return s.str();
}
inline void __evars_begin(int line) { cerr << "#" << line << ": "; }
template <typename T>
inline void __evars_out_var(vector<T> val) {
  cerr << arrStr(val, val.size());
}
template <typename T>
inline void __evars_out_var(T* val) {
  cerr << arrStr(val, 10);
}
template <typename T>
inline void __evars_out_var(T val) {
  cerr << val;
}
inline void __evars(vector<string>::iterator it) { cerr << endl; }
template <typename T, typename... Args>
inline void __evars(vector<string>::iterator it, T a, Args... args) {
  cerr << it->substr((*it)[0] == ' ', it->length()) << "=";
  __evars_out_var(a);
  cerr << "; ";
  __evars(++it, args...);
}
int const LIM = 2e6 + 3;
int const N = 1e6;
int arr[LIM + 3];
long long inf = 1e18;
int par[LIM + 3];
map<int, long long> to;
int main() {
  int tc;
  tc = 1;
  while (tc--) {
    std::vector<int> A, B, C;
    int n, k;
    cin >> n >> k;
    for (int i = 0; i < n; i++) {
      int x, a, b;
      scanf("%d %d %d", &x, &a, &b);
      if (a + b == 2) C.push_back(x);
      if (a == 1 && b == 0)
        B.push_back(x);
      else
        A.push_back(x);
    }
    sort(B.begin(), B.end());
    sort(A.begin(), A.end());
    int sz1 = A.size(), sz2 = B.size();
    for (int i = 0; i < min(sz1, sz2); i++) C.push_back(A[i] + B[i]);
    sort(C.begin(), C.end());
    if (C.size() < k)
      puts("-1");
    else {
      long long Ans = 0;
      for (auto x : C) Ans += x;
      cout << Ans;
      puts("");
    }
  }
}
