#include <bits/stdc++.h>
using namespace std;
long long gcd(long long n, long long m) {
  long long x, y;
  if (n > m) {
    y = n;
    x = m;
  } else {
    y = m;
    x = n;
  }
  if (y % x == 0)
    return x;
  else {
    return gcd(x, y % x);
  }
}
int main() {
  long long n, k, p = 0, q = 0;
  cin >> n >> k;
  vector<long long> a, b, u;
  for (long long i = 0; i < n; i++) {
    long long n1, n2, n3;
    cin >> n1 >> n2 >> n3;
    if (n2 == 1 && n3 == 1) {
      u.push_back(n1);
      p++;
      q++;
    } else if (n2 == 1) {
      a.push_back(n1);
      p++;
    } else if (n3 == 1) {
      b.push_back(n1);
      q++;
    }
  }
  if (p < k || q < k) {
    cout << -1 << endl;
    return 0;
  }
  long long x = (long long)a.size() - 1, y = (long long)b.size() - 1,
            z = (long long)u.size() - 1;
  if (a.size() > 1) sort(a.begin(), a.end());
  if (b.size() > 1) sort(b.begin(), b.end());
  if (u.size() > 1) sort(u.begin(), u.end());
  if (x == -1 || y == -1) {
    long long ans = 0;
    for (long long i = 0; i < k; i++) {
      ans += u[i];
    }
    cout << ans << endl;
    return 0;
  }
  if (z == -1) {
    long long ans = 0;
    for (long long i = 0; i < k; i++) {
      ans += a[i];
    }
    for (long long i = 0; i < k; i++) {
      ans += b[i];
    }
    cout << ans << endl;
    return 0;
  }
  long long d = 0, cost = 0;
  x = 0, y = 0;
  for (long long i = 0; i <= z; i++) {
    if (i >= k) break;
    cost += u[i];
  }
  if (z < k - 1) {
    long long i;
    for (i = 0; i < k - z - 1; i++) {
      cost += a[i];
    }
    x = i;
    for (i = 0; i < k - z - 1; i++) {
      cost += b[i];
    }
    y = i;
  }
  if (x == a.size() || y == b.size()) {
    cout << cost << endl;
    return 0;
  }
  while (a[x] + b[y] < u[z]) {
    cost = cost - u[z] + a[x] + b[y];
    x++;
    y++;
    z--;
    if (x == a.size() || y == b.size() || z < 0) break;
  }
  cout << cost << endl;
}
