#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  while (t--) {
    long long n, k;
    cin >> n >> k;
    vector<pair<long long, long long>> vec;
    long long b = 0, a = 0;
    for (long long i = 0; i < n; i++) {
      long long x, y, z;
      cin >> x >> y >> z;
      if (y and z)
        vec.push_back({x, 0}), a++, b++;
      else if (y)
        vec.push_back({x, 1}), a++;
      else if (z)
        vec.push_back({x, 2}), b++;
    }
    if (a < k or b < k) {
      cout << -1 << '\n';
      return 0;
    }
    sort(vec.begin(), vec.end());
    vector<long long> bob, alice;
    long long ans = 0;
    a = 0, b = 0;
    for (long long i = 0; i < vec.size(); i++) {
      if (a >= k and b >= k) break;
      if (vec[i].second == 0) {
        a++, b++, ans += vec[i].first;
      } else if (vec[i].second == 1 and a < k) {
        a++, ans += vec[i].first;
        alice.push_back(vec[i].first);
      } else if (vec[i].second == 2 and b < k) {
        b++, ans += vec[i].first;
        bob.push_back(vec[i].first);
      }
    }
    sort(alice.begin(), alice.end());
    sort(bob.begin(), bob.end());
    long long l = 0, m = 0;
    while ((a > k and l < alice.size()) or (b > k and m < bob.size())) {
      if (l < alice.size() and alice[l] > bob[m]) {
        ans -= alice[l];
        l++;
      } else if (m < bob.size()) {
        ans -= bob[m];
        m++;
      } else {
        if (l < alice.size()) {
          ans -= alice[l];
          l++;
        } else if (m < bob.size()) {
          ans -= bob[m];
          m++;
        }
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
