#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<pair<int, pair<int, int> > > a;
void init() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
}
void sol() {
  cin >> n >> k;
  priority_queue<int, vector<int>, greater<int> > alicecan;
  priority_queue<int, vector<int>, greater<int> > bobcan;
  priority_queue<int, vector<int>, greater<int> > both;
  priority_queue<int> aliceread;
  priority_queue<int> bobread;
  for (int i = 0; i < n; ++i) {
    int x, y, z;
    cin >> x >> y >> z;
    if (y == 1 && z == 1)
      both.push(x);
    else if (y == 1)
      alicecan.push(x);
    else
      bobcan.push(x);
  }
  if (alicecan.size() + both.size() < k) {
    cout << -1;
    return;
  }
  if (bobcan.size() + both.size() < k) {
    cout << -1;
    return;
  }
  int res = 0;
  while (alicecan.size() && aliceread.size() < k) {
    aliceread.push(alicecan.top());
    res += alicecan.top();
    alicecan.pop();
  }
  while (bobcan.size() && bobread.size() < k) {
    bobread.push(bobcan.top());
    res += bobcan.top();
    bobcan.pop();
  }
  int slgalice = aliceread.size();
  int slgbob = bobread.size();
  while (slgalice < k) {
    slgalice++;
    slgbob++;
    res += both.top();
    both.pop();
    if (slgbob > k) {
      res -= bobread.top();
      bobread.pop();
    }
  }
  while (slgbob < k) {
    slgalice++;
    slgbob++;
    res += both.top();
    both.pop();
    if (slgalice > k) {
      res -= aliceread.top();
      aliceread.pop();
    }
  }
  while (both.size()) {
    if (aliceread.top() + bobread.top() > both.top()) {
      res = res - (aliceread.top() + bobread.top()) + both.top();
      aliceread.pop();
      bobread.pop();
    }
    both.pop();
  }
  cout << res;
}
int main() {
  init();
  sol();
  return 0;
}
