#include <bits/stdc++.h>
using namespace std;
void f1(vector<long long>& a, vector<long long>& b) {
  b.resize(a.size() + 1, 0);
  for (long long i = 0; i < a.size(); i++) {
    b[i + 1] = b[i] + a[i];
  }
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n, k;
  cin >> n >> k;
  vector<long long> g11, g10, g01;
  for (long long i = 0; i < n; i++) {
    long long a, b, c;
    cin >> a >> b >> c;
    if (b & c) {
      g11.push_back(a);
    } else if (b) {
      g10.push_back(a);
    } else if (c) {
      g01.push_back(c);
    }
  }
  sort(g11.begin(), g11.end());
  sort(g10.begin(), g10.end());
  sort(g01.begin(), g01.end());
  vector<long long> s1, s2, s3;
  long long ans = -1;
  f1(g11, s1);
  f1(g10, s2);
  f1(g01, s3);
  for (long long i = 0; i <= k; i++) {
    if (i <= s1.size() && (k - i) < s2.size() && (k - i) < s3.size()) {
      long long temp = s1[i] + s2[k - i] + s3[k - i];
      if (ans == -1 || ans > temp) {
        ans = temp;
      }
    }
  }
  cout << ans << "\n";
  return 0;
}
