#include <bits/stdc++.h>
using namespace std;
void print(vector<int> a) {
  for (int i = 0; i < a.size(); i++) cout << a[i] << ' ';
  cout << endl;
}
int main() {
  int n, k;
  cin >> n >> k;
  int t[n], a[n], b[n];
  vector<int> a_b, b_b, ab_b;
  for (int i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
    if (a[i] == 1 && b[i] == 1)
      ab_b.push_back(t[i]);
    else if (a[i] == 1)
      a_b.push_back(t[i]);
    else if (b[i] == 1)
      b_b.push_back(t[i]);
  }
  int p, q, r;
  p = q = r = 0;
  int req_a = k;
  int req_b = k;
  int time = 0;
  while (req_a > 0 && req_b > 0) {
    if (req_a > 0 && req_b > 0) {
      if (r < ab_b.size() &&
          ((p < a_b.size() && q < b_b.size() && ab_b[r] < a_b[p] + b_b[q]) ||
           p == a_b.size() || q == b_b.size())) {
        time += ab_b[r];
        r++;
      } else if (p < a_b.size() && q < b_b.size()) {
        time += a_b[p] + b_b[q];
        p++, q++;
      } else {
        cout << -1 << endl;
        return 0;
      }
      req_a--;
      req_b--;
    } else if (req_a > 0) {
      if (r < ab_b.size() && (ab_b[r] < a_b[p] || p == a_b.size())) {
        time += ab_b[r];
        r++;
      } else if (p < a_b.size()) {
        time += a_b[p];
        p++;
      } else {
        cout << -1 << endl;
        return 0;
      }
      req_a--;
    } else {
      if (r < ab_b.size() && (ab_b[r] < b_b[q] || q == b_b.size())) {
        time += ab_b[r];
        r++;
      } else if (q < b_b.size()) {
        time += b_b[q];
        q++;
      } else {
        cout << -1 << endl;
        return 0;
      }
      req_b--;
    }
  }
  cout << time << endl;
  return 0;
}
