#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  long long n, k;
  cin >> n >> k;
  vector<long long> a, b, ab;
  for (long long i = 0; i < n; i++) {
    long long t, x, y;
    cin >> t >> x >> y;
    if (x == 1 && y == 1) {
      ab.push_back(t);
    } else if (x == 1) {
      a.push_back(t);
    } else if (y == 1) {
      b.push_back(t);
    }
  }
  if ((long long)(a.size() + ab.size()) < k ||
      (long long)(b.size() + ab.size()) < k) {
    cout << -1 << "\n";
    exit(0);
  }
  sort(ab.begin(), ab.end());
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  long long ans = 0;
  long long i = 0, j = 0, rep = 0;
  while (rep < k) {
    if (i < (long long)ab.size()) {
      if (j < (long long)a.size() && j < (long long)b.size()) {
        long long sum = a[j] + b[j], sab = ab[i];
        long long cnt = 1, og = j;
        while (rep + cnt < n && i < (long long)ab.size() &&
               j < (long long)a.size() && j < (long long)b.size() &&
               sum <= sab) {
          i++, j++;
          cnt++;
          sum += a[j] + b[j];
          sab += ab[i];
        }
        if (og == j) {
          ans += ab[i];
          i++;
          rep++;
        } else {
          if (j == (long long)a.size() || j == (long long)b.size()) {
            ans += sum;
          } else {
            ans += sum - (a[j] + b[j]);
          }
          rep += j - og;
        }
      } else {
        ans += ab[i];
        i++;
        rep++;
      }
    } else if (j < (long long)a.size() && j < (long long)b.size()) {
      ans += a[j] + b[j];
      j++;
      rep++;
    }
  }
  cout << ans << "\n";
  return 0;
}
