#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
void need_for_speed() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
}
int32_t main() {
  need_for_speed();
  long long t = 1;
  vector<long long> a, b, c;
  while (t--) {
    long long n, k;
    cin >> n >> k;
    long long arr[n], brr[n], crr[n];
    for (long long i = 0; i < n; i++) {
      cin >> arr[i] >> brr[i] >> crr[i];
    }
    for (long long i = 0; i < n; i++) {
      if (brr[i] == 1 and crr[i] == 1) {
        a.push_back(arr[i]);
      } else if (brr[i] == 1) {
        b.push_back(arr[i]);
      } else if (crr[i] == 1) {
        c.push_back(arr[i]);
      }
    }
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    sort(c.begin(), c.end());
    if (a.size() >= k) {
      long long sum = 0;
      long long ans = 0;
      for (long long i = 0; i < k; i++) {
        sum += a[i];
      }
      if (b.size() == 0 or c.size() == 0) {
        cout << sum << "\n";
        return 0;
      } else {
        ans = sum;
        long long d[a.size() + 1];
        for (long long i = 0; i < a.size(); i++) {
          d[i] = a[i];
        }
        for (long long i = k - 2; i >= 0; i--) {
          d[i] += d[i + 1];
        }
        long long x = min(b.size(), c.size());
        long long cnt = k - 1;
        for (long long i = 0; i < min(x, k); i++) {
          sum -= d[cnt];
          sum += b[i];
          sum += c[i];
          if (sum >= 0) ans = min(ans, sum);
          cnt--;
        }
        cout << ans << "\n";
        return 0;
      }
    } else {
      long long sum = 0;
      long long ans = 0;
      long long n = a.size();
      for (long long i = 0; i < n; i++) sum += a[i];
      long long rem = k - n;
      if (b.size() < rem or c.size() < rem) {
        cout << -1 << "\n";
        return 0;
      }
      for (long long i = 0; i < rem; i++) {
        sum += b[i];
        sum += c[i];
      }
      ans = sum;
      long long d[a.size() + 1];
      for (long long i = 0; i < a.size(); i++) {
        d[i] = a[i];
      }
      for (long long i = n - 2; i >= 0; i--) {
        d[i] += d[i + 1];
      }
      long long cnt = n - 1;
      long long x = min(b.size(), c.size());
      for (long long i = rem; i < min(n, x); i++) {
        sum -= d[cnt];
        sum += b[i];
        sum += c[i];
        if (sum > 0) ans = min(ans, sum);
        cnt--;
      }
      cout << ans << "\n";
      return 0;
    }
    cout << -1 << "\n";
    return 0;
  }
  return 0;
}
