#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> &a) {
  for (const A &it : a) out << it << " ";
  return out;
}
template <class A, class B>
istream &operator>>(istream &in, pair<A, B> &a) {
  return in >> a.first >> a.second;
}
template <class A>
istream &operator>>(istream &in, vector<A> &a) {
  for (A &i : a) in >> i;
  return in;
}
ifstream cinn("in.txt");
ofstream coutt("out.txt");
long long poww(const long long &a, long long b,
               const long long &m = (1000000007)) {
  if (b == 0) return 1;
  long long x = poww(a, b / 2, m);
  x = x * x % m;
  if (b & 1) x = x * a % m;
  return x;
}
long long ceil(const long long &a, const long long &b) {
  return (a + b - 1) / b;
}
long long n, k;
long long t[200005], a[200005], b[200005];
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> k;
  vector<long long> oo, oz, zo;
  long long wa1 = 0, wa2 = 0;
  for (long long i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
    if (a[i] + b[i] == 2)
      oo.push_back(t[i]);
    else if (a[i])
      oz.push_back(t[i]);
    else if (b[i])
      zo.push_back(t[i]);
    wa1 += a[i];
    wa2 += b[i];
  }
  if (wa1 < k || wa2 < k) {
    cout << -1;
    return 0;
  }
  sort((oo).begin(), (oo).end());
  sort((oz).begin(), (oz).end());
  sort((zo).begin(), (zo).end());
  long long p1 = k, p2 = k, ans = 0;
  for (long long i : oo) {
    ans += i;
    p1--;
    p2--;
    if (p1 <= 0 && p2 <= 0) break;
  }
  for (long long i = 0, j = 0; p1 > 0 || p2 > 0; i++, j++) {
    p1--;
    p2--;
    if (i < oz.size() && p1 >= 0) ans += oz[i];
    if (j < zo.size() && p2 >= 0) ans += zo[j];
  }
  cout << ans;
}
