#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k;
  cin >> n >> k;
  int waste = 0;
  multiset<pair<int, pair<int, int>>> mp;
  for (int i = 0; i < n; i++) {
    int time, x, y;
    cin >> time >> x >> y;
    if (x == 1 && y == 1) {
      mp.insert({-1 * time, {-1 * x, -1 * y}});
    } else {
      mp.insert({time, {-1 * x, -1 * y}});
    }
  }
  int sum = 0;
  int alice = k, bob = k;
  for (auto it = mp.begin(); it != mp.end(); it++) {
    if (it->second.first == -1 && it->second.second == -1 && alice > 0 &&
        bob > 0) {
      sum += -1 * it->first;
      alice--;
      bob--;
    } else if (it->second.first == -1 && alice > 0) {
      sum += it->first;
      alice--;
    } else if (it->second.second == -1 && bob > 0) {
      sum += it->first;
      bob--;
    }
  }
  if (alice == 0 && bob == 0) {
    cout << sum << endl;
  } else {
    cout << -1 << endl;
  }
  return 0;
}
