#include <bits/stdc++.h>
using namespace std;
template <class A, class B>
ostream& operator<<(ostream& out, const pair<A, B>& a) {
  return out << "(" << a.first << ", " << a.second << ")";
}
template <class A>
ostream& operator<<(ostream& out, const vector<A>& v) {
  out << "[";
  for (long long i = 0; i < long long(long long(v.size())); i++) {
    if (i) out << ", ";
    out << v[i];
  }
  return out << "]";
}
const long long mod = 1e9 + 7;
long long Mod(long long x) {
  x %= mod;
  if (x < 0) x += mod;
  return x;
}
long long Pow(long long x, long long n) {
  if (n == 0) return 1;
  long long t = Pow(x, n / 2);
  t = Mod(t * t);
  if (n & 1) t = Mod(t * x);
  return t;
}
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
struct ds {
  long long t, x, y;
};
bool cmp(ds l, ds r) {
  if (l.t < r.t)
    return true;
  else if (l.t == r.t) {
    return l.x + l.y > r.x + r.y;
  } else
    return false;
}
long long main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long n, k;
  cin >> n >> k;
  vector<ds> a(n);
  for (long long i = 0; i < n; i++) {
    cin >> a[i].t >> a[i].x >> a[i].y;
  }
  sort(a.begin(), a.end(), cmp);
  long long x = 0, y = 0;
  long long ans = 0;
  vector<long long> xx, yy, common;
  for (long long i = 0; i < n; i++) {
    if (x < k and y < k) {
      ans += a[i].t;
      if (a[i].x) x++;
      if (a[i].y) y++;
    } else if (x < k and a[i].x) {
      ans += a[i].t;
      x++;
    } else if (y < k and a[i].y) {
      ans += a[i].t;
      y++;
    }
    if (a[i].x and a[i].y)
      common.push_back(a[i].t);
    else if (a[i].x)
      xx.push_back(a[i].t);
    else if (a[i].y)
      yy.push_back(a[i].t);
  }
  if (x < k or y < k) {
    cout << "-1" << endl;
    return 0;
  }
  for (long long i = 1; i < common.size(); i++) {
    common[i] += common[i - 1];
  }
  for (long long i = 1; i < xx.size(); i++) xx[i] += xx[i - 1];
  for (long long i = 1; i < yy.size(); i++) yy[i] += yy[i - 1];
  for (long long i = 0; i < common.size(); i++) {
    long long c = i + 1;
    long long t = common[i];
    if (k - c <= xx.size() and k - c <= yy.size() and k - c >= 1) {
      long long r = k - c;
      t += xx[r - 1];
      t += yy[r - 1];
      ans = min(ans, t);
    } else if (c >= k) {
      ans = min(ans, t);
    }
  }
  cout << ans << endl;
}
