#include <bits/stdc++.h>
using namespace std;
int n, k;
struct book {
  int t, a, b;
} B;
bool operator<(book A, book B) { return (A.t >= B.t); }
int main() {
  vector<book> v;
  int ans = 0, ali = 0, bob = 0;
  scanf("%d%d", &n, &k);
  for (int i = 0; i < n; i++) {
    int x, y, z;
    scanf("%d%d%d", &x, &y, &z);
    if (z == 0 && y == 0)
      continue;
    else {
      B.t = x;
      B.a = y;
      B.b = z;
      if (y) ali++;
      if (z) bob++;
      v.push_back(B);
      ans += x;
    }
  }
  if (ali < k || bob < k) {
    printf("%d", -1);
    printf("\n");
    return 0;
  }
  sort(v.begin(), v.end());
  for (int i = 0; i < v.size(); i++) {
    if (v[i].a) ali--;
    if (v[i].b) bob--;
    if (bob >= k && ali >= k)
      ans -= v[i].t;
    else {
      if (v[i].a) ali++;
      if (v[i].b) bob++;
    }
  }
  printf("%d", ans);
  return 0;
}
