#include <bits/stdc++.h>
using namespace std;
const int MaxN = 2e5 + 5;
int n, k;
struct NODE {
  double t;
  int A, B, V;
} a[MaxN];
stack<double> AA, BB;
bool cmp(NODE x, NODE y) {
  if (x.t != y.t) return x.t < y.t;
  return x.V > y.V;
}
int main() {
  scanf("%d %d", &n, &k);
  for (int i = 1; i <= n; i++) {
    scanf("%lf %d %d", &a[i].t, &a[i].A, &a[i].B);
    if (a[i].A && a[i].B) {
      a[i].V = 1;
      a[i].t /= 2.0;
    }
  }
  sort(a + 1, a + 1 + n, cmp);
  int ak = k, bk = k;
  double ans = 0;
  for (int i = 1; i <= n; i++) {
    if (a[i].V && (ak || bk)) {
      if (!ak) {
        AA.pop();
        bk--;
      } else if (!bk) {
        BB.pop();
        ak--;
      } else {
        ak--;
        bk--;
      }
      ans += a[i].t * 2.0;
    } else {
      if (a[i].A && ak > 0) {
        ak--;
        AA.push(a[i].t);
      }
      if (a[i].B && bk > 0) {
        bk--;
        BB.push(a[i].t);
      }
    }
  }
  if (ak || bk) {
    printf("-1\n");
    return 0;
  }
  while (!AA.empty()) {
    ans += AA.top();
    AA.pop();
  }
  while (!BB.empty()) {
    ans += BB.top();
    BB.pop();
  }
  printf("%d\n", (int)(ans));
}
