#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n, k;
  cin >> n >> k;
  vector<int> a;
  vector<int> b;
  vector<int> c;
  a.push_back(0), b.push_back(0), c.push_back(0);
  for (int i = 0; i < n; i++) {
    int x, l, m;
    cin >> x >> l >> m;
    if (l == 1 && m == 1) {
      c.push_back(x);
    } else if (l == 1)
      a.push_back(x);
    else if (m == 1)
      b.push_back(x);
  }
  sort(a.begin() + 1, a.end());
  sort(b.begin() + 1, b.end());
  sort(c.begin() + 1, c.end());
  if (a.size() + c.size() - 2 < k || c.size() + b.size() - 2 < k) {
    cout << -1 << endl;
    return 0;
  }
  int optimal = INT_MAX;
  for (int i = 1; i < a.size(); i++) a[i] = a[i] + a[i - 1];
  for (int i = 1; i < b.size(); i++) b[i] = b[i] + b[i - 1];
  for (int i = 1; i < c.size(); i++) c[i] = c[i] + c[i - 1];
  int l = 0;
  int check = min(a.size(), b.size()) - 1;
  if (k - check > 0) {
    l += k - check;
  }
  for (int i = l; i <= k; i++) {
    optimal = min(optimal, c[l] + a[k - l] + b[k - l]);
  }
  cout << optimal << endl;
  return 0;
}
