#include <bits/stdc++.h>
using namespace std;
const long long int inf = 1e18;
const long long int mod = 1e9 + 7;
const long long int mod2 = 998244353;
const long long int longinf = 1LL << 60;
const long double pi = acos(-1);
const long double phi = (sqrt(5) + 1) / 2;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int n, k;
  cin >> n >> k;
  vector<long long int> t(n), a(n), b(n);
  for (long long int i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
  }
  long long int k1 = k;
  long long int k2 = k;
  vector<long long int> x;
  vector<long long int> y;
  vector<long long int> comm;
  long long int ans = 0;
  for (long long int i = 0; i < n; i++) {
    if (k1 == 0 && k2 == 0) {
      break;
    }
    if (a[i] == 1 && b[i] == 1) {
      comm.push_back(t[i]);
      k1--;
      k2--;
    } else if (a[i] == 1) {
      x.push_back(t[i]);
    } else if (b[i] == 1) {
      y.push_back(t[i]);
    }
  }
  if (k1 == 0 && k2 == 0) {
    sort(comm.begin(), comm.end());
    for (long long int i = 0; i < k; i++) {
      ans += comm[i];
    }
  } else {
    for (long long int i = 0; i < (long long int)comm.size(); i++) {
      ans += comm[i];
    }
    sort(x.begin(), x.end());
    sort(y.begin(), y.end());
    if (x.size() < k1 || y.size() < k2) {
      cout << "-1" << endl;
      return 0;
    }
    for (long long int i = 0; i < k1; i++) {
      ans += x[i];
    }
    for (long long int i = 0; i < k2; i++) {
      ans += y[i];
    }
  }
  cout << ans << endl;
  return 0;
}
