#include <bits/stdc++.h>
using namespace std;
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1, -1, 1, -1, 0, 0, -1, 1};
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
const double pi = acos(-1.0);
const double eps = 1e-6;
const int mod = (int)1e9 + 7;
const int maxn = 300005;
const int logn = 20;
int tim[maxn], a[maxn], b[maxn];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  int t = 1;
  while (t--) {
    int n, k;
    cin >> n >> k;
    multiset<int> took;
    multiset<int> alic, bob;
    vector<int> both;
    for (int i = 1; i <= (n); i++) {
      cin >> tim[i] >> a[i] >> b[i];
      if (a[i] == 1 && b[i] == 1)
        both.push_back(tim[i]);
      else if (a[i] == 1)
        alic.insert(tim[i]);
      else
        bob.insert(tim[i]);
    }
    long long tot = 0LL;
    int ac = 0, bc = 0;
    if (both.size() > 0) {
      sort(both.begin(), both.end());
      for (int x : both) {
        took.insert(x);
        if (took.size() == k) break;
      }
      if (took.size() < k) {
        while (1) {
          if (took.size() == k) break;
          if (alic.size() == 0 || bob.size() == 0) break;
          took.insert((*alic.begin()) + (*bob.begin()));
          alic.erase(alic.begin());
          bob.erase(bob.begin());
        }
      }
      while (1) {
        if (took.size() == 0) break;
        if (alic.size() == 0 || bob.size() == 0) break;
        int cur = *took.rbegin();
        int alt = (*alic.begin()) + (*bob.begin());
        if (alt >= cur) break;
        tot += alt;
        took.erase(took.lower_bound(cur));
        alic.erase(alic.begin());
        bob.erase(bob.begin());
        ac++;
        bc++;
      }
    }
    ac += took.size();
    bc += took.size();
    for (int x : took) tot += x;
    for (int x : alic) {
      if (ac == k) break;
      ac++;
      tot += x;
    }
    for (int x : bob) {
      if (bc == k) break;
      bc++;
      tot += x;
    }
    if (ac < k || bc < k)
      cout << "-1\n";
    else
      cout << tot << "\n";
  }
  return 0;
}
