#include <bits/stdc++.h>
using namespace std;
long long setBit(long long mask, int p) { return (mask | (1 << p)); }
long long resetBit(long long mask, int p) { return (mask & ~(1 << p)); }
long long flipBit(long long mask, int p) { return (mask ^ (1 << p)); }
bool check(long long mask, int p) { return (mask & (1 << p)); }
int msb(long long N) { return N ? 63 - __builtin_clzll(N) : -1; }
int lsb(long long N) { return __builtin_ffs(N) - 1; }
int countOn(long long mask) { return __builtin_popcountll(mask); }
int countOff(long long mask) { return msb(mask) - countOn(mask) + 1; }
long long bigmod(long long N, long long P) {
  if (P == 0) return 1;
  if (P % 2 == 0) {
    long long ret = bigmod(N, P / 2) % 1000000007;
    return (ret * ret) % 1000000007;
  }
  return ((N % 1000000007) * (bigmod(N, P - 1) % 1000000007)) % 1000000007;
}
long long modInverse(long long a) { return bigmod(a, 1000000007 - 2); }
mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
long long rnd(long long l, long long r) {
  return (mt_rnd_64() % (r - l + 1)) + l;
}
struct book {
  int t, c1, c2;
  book(int a, int b, int c) {
    t = a;
    c1 = b;
    c2 = c;
  }
  book() {}
};
bool cmp(book a, book b) {
  if (a.t == b.t) return (a.c1 * a.c2) > (b.c1 * b.c2);
  return a.t < b.t;
}
int main() {
  int n, k, i;
  scanf("%d", &n);
  scanf("%d", &k);
  vector<book> a;
  a.clear();
  vector<int> both, alice, bob, alicedoes, bobdoes;
  vector<int> X, Y, Z;
  for (i = 1; i <= n; i++) {
    int x, y, z;
    scanf("%d", &x);
    scanf("%d", &y);
    scanf("%d", &z);
    X.push_back(x);
    Y.push_back(y);
    Z.push_back(z);
    book b = book(x, y, z);
    if (b.c1) alicedoes.push_back(b.t);
    if (b.c2) bobdoes.push_back(b.t);
    if (b.c1 && b.c2)
      both.push_back(b.t);
    else if (b.c1)
      alice.push_back(b.t);
    else if (b.c2)
      bob.push_back(b.t);
    a.push_back(b);
  }
  sort(a.begin(), a.end(), cmp);
  int A = k, B = k;
  long long ans1 = 0;
  for (i = 0; i < n; i++) {
    int f1 = 0, f2 = 0;
    if (a[i].c1 && A) A--, f1 = 1;
    if (a[i].c2 && B) B--, f2 = 1;
    if (f1 || f2) ans1 += a[i].t;
  }
  sort(both.begin(), both.end());
  sort(bob.begin(), bob.end());
  sort(alice.begin(), alice.end());
  int bothsz = both.size(), asz = alice.size(), bsz = bob.size();
  long long ans = 0;
  for (i = 0; i < bothsz; i++) {
    ans += both[i];
    k--;
    if (!k) break;
  }
  if (k) {
    int k1 = k;
    int k2 = k;
    for (i = 0; i < asz; i++) {
      ans += alice[i];
      k1--;
      if (!k1) break;
    }
    for (i = 0; i < bsz; i++) {
      ans += bob[i];
      k2--;
      if (!k2) break;
    }
  }
  if (alicedoes.size() < k || bobdoes.size() < k)
    printf("-1");
  else
    printf("%lld\n", min(ans, ans1));
}
