#include <bits/stdc++.h>
#pragma warning(disable : 4996)
using namespace std;
const long long P = 998244353;
const long long MaxN = 2000010;
const long double pi = 3.14159265358979323846264338;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long T = 1;
  for (long long q = 0; q < (T); q++) {
    long long n, k, a = 0, b = 0, ans = 0;
    cin >> n >> k;
    vector<pair<long long, long long> > u;
    for (long long i = 0; i < (n); i++) {
      long long t, x, y;
      cin >> t >> x >> y;
      if (x + y == 2)
        a++, b++, u.push_back({t, 2});
      else if (x + y == 1) {
        if (x)
          a++, u.push_back({t, 1});
        else
          b++, u.push_back({t, 0});
      }
    }
    if (a < k || b < k) {
      cout << -1 << "\n";
      continue;
    }
    sort(u.begin(), u.end());
    a = 0, b = 0;
    long long pos = u.size() - 1;
    for (long long i = 0; i < (u.size()); i++) {
      if (u[i].second == 2)
        a++, b++;
      else if (u[i].second == 1)
        a++;
      else
        b++;
      ans += u[i].first;
      if (min(a, b) == k) {
        pos = i;
        break;
      }
    }
    if (a > b) {
      while (a != k) {
        if (u[pos].second == 1) ans -= u[pos].first, a--;
        pos--;
      }
    } else if (b > a) {
      while (b != k) {
        if (u[pos].second == 0) ans -= u[pos].first, b--;
        pos--;
      }
    }
    cout << ans << "\n";
  }
  cerr << "Time : " << ((double)clock()) / (double)CLOCKS_PER_SEC << "s\n";
  return 0;
}
