#include <bits/stdc++.h>
using namespace std;
template <class T>
T nrem(T x, T y) {
  return ((x % y) + y) % y;
}
void in() {}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  in();
  int t, k;
  cin >> t >> k;
  vector<int> same;
  map<int, int> alice, bob;
  while (t--) {
    int t, a, b;
    cin >> t >> a >> b;
    if (a == b && a == 1)
      same.push_back(t);
    else {
      if (a)
        alice[t]++;
      else
        bob[t]++;
    }
  }
  if (same.size() == 0) return cout << -1 << "\n", 0;
  if (same.size() > k) {
    int sum = 0;
    for (int i = 0; i < k; ++i) sum += same[i];
  } else {
    int rem = k - same.size();
    int sum = 0;
    for (int i = 0; i < same.size(); ++i) sum += same[i];
    auto it = alice.begin(), bit = bob.begin();
    while (rem--) {
      if (it == alice.end() || bit == bob.end()) return cout << -1 << "\n", 0;
      sum += it->first;
      sum += bit->first;
      it++;
      bit++;
    }
    cout << sum << "\n";
  }
}
