#include <bits/stdc++.h>
using namespace std;
long long int preb[200005], preo[200005], prea[200005];
vector<long long int> ortak;
vector<long long int> va;
vector<long long int> vb;
int main() {
  long long int n, k;
  cin >> n >> k;
  for (long long int i = 0; i < n; i++) {
    bool a, b;
    long long int x;
    cin >> x >> a >> b;
    if (a == b && b == 1) {
      ortak.push_back(x);
    } else if (a == 1) {
      va.push_back(x);
    } else {
      vb.push_back(x);
    }
  }
  sort(va.begin(), va.end());
  sort(ortak.begin(), ortak.end());
  sort(vb.begin(), vb.end());
  for (long long int i = 0; i < va.size(); i++) {
    prea[i + 1] = prea[i] + va[i];
  }
  for (long long int i = 0; i < vb.size(); i++) {
    preb[i + 1] = preb[i] + vb[i];
  }
  for (long long int i = 0; i < ortak.size(); i++) {
    preo[i + 1] = preo[i] + ortak[i];
  }
  long long int cvp = -1;
  for (long long int i = 0; i <= ortak.size(); i++) {
    if (k - i <= va.size() && k - i <= vb.size())
      cvp = (cvp > preo[i] + prea[k - i + 1] + preb[k - i + 1]
                 ? cvp
                 : preo[i] + prea[k - i + 1] + preb[k - i + 1]);
  }
  cout << cvp << "\n";
}
