#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, k, i, ok, s = 0, sum = 0, ans = 0;
  multimap<long long, long long> pi1, pi2, pi3;
  multimap<long long, long long>::iterator it;
  cin >> n >> ok;
  long long a, b, c;
  for (i = 0; i < n; i++) {
    cin >> a >> b >> c;
    if (b == 1) {
      if (b + c == 2)
        k = 0;
      else
        k = 2;
      pi1.insert({a, k});
    }
    if (c == 1) {
      if (b + c == 2)
        k = 0;
      else
        k = 2;
      pi2.insert({a, k});
    }
  }
  long long x = pi1.size();
  long long y = pi2.size();
  if (x < ok || y < ok) {
    cout << -1 << endl;
  } else {
    for (it = pi1.begin(); it != pi1.end(); it++) {
      pi3.insert({it->second, it->first});
    }
    pi1.clear();
    for (it = pi3.begin(); it != pi3.end(); it++) {
      pi1.insert({it->second, it->first});
    }
    pi3.clear();
    s = 0;
    long long z = ok;
    for (it = pi1.begin(); it != pi1.end(); it++) {
      s++;
      ans += it->first;
      if (it->second == 0) z--;
      if (s == ok) break;
    }
    for (it = pi2.begin(); it != pi2.end(); it++) {
      pi3.insert({it->second, it->first});
    }
    pi2.clear();
    for (it = pi3.begin(); it != pi3.end(); it++) {
      pi2.insert({it->second, it->first});
    }
    pi3.clear();
    s = 0;
    for (it = pi2.begin(); it != pi2.end(); it++) {
      if (s == z) break;
      if (it->second == 2) {
        ans += it->first;
        s++;
      }
    }
    cout << ans << endl;
  }
}
