#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
long long int lcm(long long int a, long long int b) {
  return (a * b) / gcd(a, b);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int t = 1;
  while (t--) {
    long long int n, k, i, j;
    cin >> n >> k;
    vector<long long int> both, alice, bob;
    for (i = 0; i < n; i++) {
      long long int t, a, b;
      cin >> t >> a >> b;
      if (a == 1 && a == b)
        both.push_back(t);
      else if (a == 1)
        alice.push_back(t);
      else if (b == 1)
        bob.push_back(t);
    }
    sort(alice.begin(), alice.end());
    sort(both.begin(), both.end());
    sort(bob.begin(), bob.end());
    long long int both_size = both.size();
    long long int alice_size = alice.size();
    long long int bob_size = bob.size();
    if (both_size + alice_size < k || both_size + bob_size < k) {
      cout << -1 << endl;
    } else {
      long long int time = 0;
      long long int x = 0, y = 0;
      while (k) {
        if (x < both_size && y < alice_size && y < bob_size) {
          if (both[x] >= alice[y] + bob[y]) {
            time += both[x];
            x++;
          } else {
            time += (alice[y] + bob[y]);
            y++;
          }
          k--;
        } else if (x < both_size) {
          time += both[x];
          x++;
          k--;
        } else if (y < alice_size && y < bob_size) {
          time += (alice[y] + bob[y]);
          y++;
          k--;
        }
      }
      cout << time << endl;
    }
  }
}
