#include <bits/stdc++.h>
using namespace std;
long long M = 998244353;
long long powerm(long long x, long long y) {
  long long res = 1;
  while (y) {
    if (y & 1) res = (res * x) % M;
    y = y >> 1;
    x = (x * x) % M;
  }
  return res % M;
}
long long power(long long x, long long y) {
  long long res = 1;
  while (y) {
    if (y & 1) res = (res * x);
    y = y >> 1;
    x = (x * x);
  }
  return res;
}
const int N = 5e5 + 5;
long long fact[N], inv[N];
void pre(int n) {
  fact[0] = inv[0] = 1;
  for (long long i = 1; i <= n; i++) {
    fact[i] = (fact[i - 1] * i) % M;
    inv[i] = powerm(fact[i], M - 2);
  }
}
long long C(long long n, long long r) {
  long long ans = ((fact[n] * inv[r]) % M + M) % M;
  ans = ((ans * inv[n - r]) % M + M) % M;
  return ans;
}
bool myfunc(pair<int, int> p1, pair<int, int> p2) {
  if (p1.first == p2.first) {
    return p1.second < p2.second;
  }
  return p1.first < p2.first;
}
int main() {
  int t = 1;
  while (t--) {
    vector<long long> v1, v2, v3;
    long long n, k, a, b, c;
    cin >> n >> k;
    for (long long i = 0; i < n; i++) {
      cin >> a >> b >> c;
      if (b == 0 && c == 1) v1.push_back(a);
      if (b == 1 && c == 0) v2.push_back(a);
      if (b == 1 && c == 1) v3.push_back(a);
    }
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());
    sort(v3.begin(), v3.end());
    long long l1 = min((long long)v1.size(), (long long)v2.size());
    long long l2 = v3.size();
    if (l1 + l2 < k) {
      cout << -1 << endl;
      continue;
    }
    long long ptr1 = 0, ptr2 = 0;
    long long ans = 0, ct = 0;
    while (ptr1 < l1 && ptr2 < l2 && ct < k) {
      if (v1[ptr1] + v2[ptr1] <= ptr2) {
        ans += v1[ptr1] + v2[ptr1];
        ptr1++;
      } else {
        ans += v3[ptr2];
        ptr2++;
      }
      ct++;
    }
    if (ct == k)
      cout << ans << endl;
    else {
      if (ptr1 == l1) {
        while (ct < k) {
          ans += v3[ptr2];
          ptr2++;
          ct++;
        }
      }
      if (ptr2 == l2) {
        while (ct < k) {
          ans += v1[ptr1] + v2[ptr1];
          ptr1++;
          ct++;
        }
      }
    }
    cout << ans << endl;
  }
}
