#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k;
  cin >> n >> k;
  int ar[n][3];
  vector<int> a, b, c;
  for (int i = 0; i < n; i++) {
    cin >> ar[i][2] >> ar[i][0] >> ar[i][1];
    if (ar[i][0] == 1) {
      if (ar[i][1] == 1) {
        c.push_back(ar[i][2]);
      } else {
        a.push_back(ar[i][2]);
      }
    } else {
      b.push_back(ar[i][2]);
    }
  }
  if (a.size() + c.size() < k || b.size() + c.size() < k) {
    cout << -1;
    return 0;
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  sort(c.begin(), c.end());
  int abpointer = 0;
  int cpointer = 0;
  int sum = 0;
  int cost = 0;
  while (sum < k) {
    if (abpointer < a.size() && abpointer < b.size() && cpointer < c.size() &&
        a[abpointer] + b[abpointer] < c[cpointer]) {
      sum++;
      cost += a[abpointer] + b[abpointer];
      abpointer++;
    } else if (abpointer < a.size() && abpointer < b.size() &&
               cpointer < c.size() &&
               a[abpointer] + b[abpointer] >= c[cpointer]) {
      sum++;
      cost += c[cpointer];
      cpointer++;
    } else if (abpointer < a.size() && abpointer < b.size()) {
      sum++;
      cost += a[abpointer] + b[abpointer];
      abpointer++;
    } else if (cpointer < c.size()) {
      sum++;
      cost += c[cpointer];
      cpointer++;
    }
  }
  cout << cost << endl;
}
