#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
char *fs, *ft, buf[1 << 20];
inline long long read() {
  long long x = 0, f = 1;
  char ch =
      (fs == ft && (ft = (fs = buf) + fread(buf, 1, 1 << 20, stdin), fs == ft))
          ? 0
          : *fs++;
  ;
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = (fs == ft &&
          (ft = (fs = buf) + fread(buf, 1, 1 << 20, stdin), fs == ft))
             ? 0
             : *fs++;
    ;
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = (fs == ft &&
          (ft = (fs = buf) + fread(buf, 1, 1 << 20, stdin), fs == ft))
             ? 0
             : *fs++;
    ;
  }
  return x * f;
}
using namespace std;
const long long N = 2e5 + 5;
const long long inf = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
const double eps = 1e-7;
const double PI = acos(-1);
struct node {
  long long t, a, b;
} e[N];
bool cmp(node a, node b) { return a.t < b.t; }
long long n, k;
long long solve(vector<node> a, vector<node> b, vector<node> c) {
  long long res = 0, cnt1 = 0, cnt2 = 0, posa = 0, posb = 0, posc = 0;
  while (cnt1 < k) {
    long long xa = inf, xc = inf;
    if (posa < a.size()) xa = a[posa].t;
    if (posc < c.size()) xc = c[posc].t;
    res += min(xa, xc);
    cnt1++;
    if (xa <= xc)
      posa++;
    else {
      posc++;
      cnt2++;
    }
  }
  while (cnt2 < k) {
    long long xb = inf, xc = inf;
    if (posb < b.size()) xb = b[posb].t;
    if (posc < c.size()) xc = c[posc].t;
    res += min(xb, xc);
    cnt2++;
    if (xb <= xc)
      posb++;
    else {
      posc++;
    }
  }
  return res;
}
signed main() {
  cin >> n >> k;
  vector<node> a, b, c;
  for (long long i = 1; i <= n; i++) {
    cin >> e[i].t >> e[i].a >> e[i].b;
    if (e[i].a == 1 && e[i].b == 1)
      c.push_back(e[i]);
    else if (e[i].a == 1)
      a.push_back(e[i]);
    else
      b.push_back(e[i]);
  }
  sort(a.begin(), a.end(), cmp);
  sort(b.begin(), b.end(), cmp);
  sort(c.begin(), c.end(), cmp);
  if (c.size() + a.size() < k || b.size() + c.size() < k)
    cout << -1 << '\n';
  else
    cout << min(solve(a, b, c), solve(b, a, c)) << '\n';
}
