#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k;
  cin >> n >> k;
  vector<long long> a;
  vector<long long> b;
  vector<long long> bo;
  for (int i = 0; i < n; ++i) {
    int tt, tt1, tt2;
    cin >> tt >> tt1 >> tt2;
    if (tt1 == 1 && tt2 == 1)
      bo.push_back(tt);
    else if (tt1 == 1)
      b.push_back(tt);
    else if (tt2 == 1)
      a.push_back(tt);
  }
  sort(bo.begin(), bo.end());
  long long sum = 0;
  int l1 = 0;
  if (bo.size() > k)
    l1 = k;
  else
    l1 = bo.size();
  for (int i = 0; i < l1; ++i) {
    sum += bo[i];
  }
  long long kl1 = k - l1;
  if (kl1 > a.size() || kl1 > b.size()) {
    cout << "-1\n";
    return 0;
  }
  if (kl1 > 0) {
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
  } else {
    cout << sum << "\n";
    return 0;
  }
  long long p1 = 0, p2 = 0;
  while (p1 < kl1 || p2 < kl1) {
    if (a[p1] <= b[p2] && p1 < kl1) {
      sum += a[p1];
      p1++;
    } else if (p2 < kl1) {
      sum += b[p2];
      p2++;
    } else if (p1 < kl1) {
      sum += a[p1];
      p1++;
    }
  }
  cout << sum << "\n";
}
