#include <bits/stdc++.h>
using namespace std;
double pi = acos(-1);
void OJ() {}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long n, k, s = 0, s_ = 0, c = 0;
  cin >> n >> k;
  unordered_set<long long> s1, s2, s3;
  priority_queue<pair<long long, long long>, vector<pair<long long, long long>>,
                 greater<pair<long long, long long>>>
      pa, push_back;
  for (long long i = 0; i < n; i++) {
    long long a, b, c;
    cin >> a >> b >> c;
    if (b == 1) {
      s1.insert(i);
      pa.push({a, i});
    }
    if (c == 1) {
      s2.insert(i);
      push_back.push({a, i});
    }
  }
  if (s1.size() < k or s2.size() < k) {
    cout << "-1";
    return 0;
  }
  if (pa.size() > push_back.size()) {
    long long c = 0;
    while (!push_back.empty() and c < k) {
      c++;
      s += (push_back.top().first);
      s3.insert(push_back.top().second);
      push_back.pop();
    }
    c = 0;
    for (auto i : s3) {
      if (s1.count(i)) c++;
    }
    if (c < k) {
      while (!pa.empty() and c < k) {
        if (s3.find(pa.top().second) == s3.end()) {
          s_ += (pa.top().first);
        }
        c++;
        pa.pop();
      }
    }
  } else {
    long long c = 0;
    while (!pa.empty() and c < k) {
      c++;
      s += (pa.top().first);
      s3.insert(pa.top().second);
      pa.pop();
    }
    c = 0;
    for (auto i : s3) {
      if (s2.count(i)) c++;
    }
    if (c < k) {
      while (!push_back.empty() and c < k) {
        if (s3.find(push_back.top().second) == s3.end()) {
          s_ += (push_back.top().first);
        }
        c++;
        push_back.pop();
      }
    }
  }
  cout << s + s_;
}
