#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int n, k;
  cin >> n >> k;
  vector<int> a, b, c;
  c.push_back(0);
  a.push_back(0);
  b.push_back(0);
  for (int i = 0; i < n; ++i) {
    int t, x, y;
    cin >> t >> x >> y;
    if (x == 1 and y == 1) {
      c.push_back(t);
    } else if (x == 1) {
      a.push_back(t);
    } else if (y == 1) {
      b.push_back(t);
    }
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  sort(c.begin(), c.end());
  int n1 = a.size();
  int n2 = b.size();
  int n3 = c.size();
  for (int i = 1; i < n1; ++i) {
    a[i] += a[i - 1];
  }
  for (int i = 1; i < n2; ++i) {
    b[i] += b[i - 1];
  }
  for (int i = 1; i < n3; ++i) {
    c[i] += c[i - 1];
  }
  int max_ans = 1e9;
  for (int i = 0; i < n3; ++i) {
    int val = c[i];
    int left = k - i;
    if (n1 > left and n2 > left) {
      val += a[left];
      val += b[left];
      max_ans = min(max_ans, val);
    }
  }
  if (max_ans == 1e9) {
    max_ans = -1;
  }
  cout << max_ans << '\n';
  return 0;
}
