#include <bits/stdc++.h>
using namespace std;
struct book {
  int time, a, b;
} bk[200010];
queue<book> q1, q2, q3;
int cmp(book a, book b) { return a.time > b.time; }
int main() {
  int k, t, x, y, n;
  long long rzt = 0;
  book a, b, c;
  x = 0;
  y = 0;
  scanf("%d%d", &n, &k);
  for (int l1 = 0; l1 < n; l1++) {
    scanf("%d%d%d", &bk[l1].time, &bk[l1].a, &bk[l1].b);
    if (bk[l1].a) x++;
    if (bk[l1].b) y++;
  }
  if (x < k || y < k) {
    printf("-1\n");
    return 0;
  }
  x = 0;
  y = 0;
  sort(bk, bk + n, cmp);
  for (int l1 = 0; l1 < n; l1++) {
    if (bk[l1].a && bk[l1].b) {
      q1.push(bk[l1]);
    } else {
      if (bk[l1].a) {
        q2.push(bk[l1]);
      }
      if (bk[l1].b) {
        q3.push(bk[l1]);
      }
    }
  }
  while (x < k) {
    if (q1.empty()) {
    }
    if (!q2.empty() && !q3.empty() && !q1.empty()) {
      a = q2.front();
      b = q3.front();
      c = q1.front();
      if (a.time + b.time <= c.time) {
        rzt += a.time;
        rzt += b.time;
        x++;
        q2.pop();
        q3.pop();
      } else {
        rzt += c.time;
        x++;
        q1.pop();
      }
    } else {
      if (q2.empty() || q3.empty()) {
        c = q1.front();
        rzt += c.time;
        x++;
        q1.pop();
      } else {
        a = q2.front();
        b = q3.front();
        rzt += a.time;
        rzt += b.time;
        x++;
        q2.pop();
        q3.pop();
      }
    }
  }
  printf("%lld\n", rzt);
}
