#include <bits/stdc++.h>
using namespace std;
bool comp(pair<int, pair<int, int>> a, pair<int, pair<int, int>> b) {
  if (a.first < b.first) return 1;
  if (a.first > b.first) return 0;
  return a.second.second + a.second.first > b.second.second + b.second.first;
}
int main(void) {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, k;
  cin >> n >> k;
  vector<pair<int, pair<int, int>>> two;
  int suma = 0, sumb = 0;
  for (int i = 1; i <= n; i++) {
    int t, a, b;
    cin >> t >> a >> b;
    suma += a, sumb += b;
    if (a + b > 0) two.push_back({t, {a, b}});
  }
  if (suma < k || sumb < k) {
    cout << -1 << endl;
    return 0;
  }
  sort(two.begin(), two.end(), comp);
  int a = k, b = k;
  int mn = 0;
  int i = 0;
  vector<int> al, bb;
  while (i++ < two.size() && (a + b != 0)) {
    pair<int, pair<int, int>> p = two[i - 1];
    if (a == 0 && p.second.second == 0) continue;
    if (b == 0 && p.second.first == 0) continue;
    if (p.second.first + p.second.second == 2) {
      mn += p.first;
      if (a == 0 && al.size() >= 1) {
        al.pop_back(), b -= 1;
      } else if (b == 0 && bb.size() >= 1) {
        bb.pop_back(), a -= 1;
      } else {
        a -= 1, b -= 1;
      }
    } else {
      if (p.second.first == 1)
        al.push_back(p.first);
      else
        bb.push_back(p.first);
      a -= p.second.first;
      b -= p.second.second;
    }
  }
  if (al.size() != bb.size())
    cout << "NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" << endl;
  else {
    for (int i = 0; i < al.size(); i++) mn += al[i];
    for (int i = 0; i < bb.size(); i++) mn += bb[i];
    cout << mn << endl;
  }
  return 0;
}
