#include <bits/stdc++.h>
using namespace std;
double pi = 2 * acos(0.0);
int i, j;
int cmp(pair<long long, pair<long long, long long>> x,
        pair<long long, pair<long long, long long>> y) {
  auto it1 = x;
  auto it2 = y;
  if (it1.first < it2.first) return 1;
  if (it1.first == it2.first && it1.second.first + it1.second.second >
                                    it2.second.first + it2.second.second)
    return 1;
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long n, k, ans = 0;
  cin >> n >> k;
  multiset<long long> a, b, both;
  multiset<long long>::iterator ita, itb, itboth;
  long long likea = 0, likeb = 0;
  for (i = 0; i < n; i++) {
    long long t, x, y;
    cin >> t >> x >> y;
    if (x & y)
      both.insert(t), likea++, likeb++;
    else if (x)
      a.insert(t), likea++;
    else
      b.insert(t), likeb++;
  }
  if (likea < k || likeb < k) {
    cout << -1 << endl;
    return 0;
  } else {
    ita = a.begin();
    itb = b.begin();
    itboth = both.begin();
    long long al = k, bl = k;
    while (al > 0 || bl > 0) {
      if (al > 0 && bl > 0) {
        if (ita == a.end() || itb == b.end()) {
          ans += *itboth;
          itboth++;
          al--;
          bl--;
        } else {
          if (itboth != both.end()) {
            if (*ita + *itb < *itboth) {
              ans += *ita + *itb;
              ita++;
              itb++;
              al--;
              bl--;
            } else {
              ans += *itboth;
              itboth++;
              al--;
              bl--;
            }
          } else {
            ans += *ita;
            ans += *itb;
            ita++;
            itb++;
            al--;
            bl--;
          }
        }
      } else if (al > 0) {
        if (itboth == both.end()) {
          ans += *ita;
          ita++;
          al--;
        } else if (ita == a.end()) {
          ans += *itboth;
          itboth++;
          al--;
          bl--;
        } else {
          if (*ita < *itboth) {
            ans += *ita;
            ita++;
            al--;
          } else {
            ans += *itboth;
            itboth++;
            al--;
            bl--;
          }
        }
      } else if (bl > 0) {
        if (itboth == both.end()) {
          ans += *itb;
          itb++;
          bl--;
        } else if (itb == a.end()) {
          ans += *itboth;
          itboth++;
          bl--;
          al--;
        } else {
          if (*itb < *itboth) {
            ans += *itb;
            itb++;
            bl--;
          } else {
            ans += *itboth;
            itboth++;
            bl--;
            al--;
          }
        }
      }
    }
  }
  cout << ans << endl;
}
