#include <bits/stdc++.h>
using namespace std;
struct book {
  long long x;
  int y, z;
};
bool comp(book &b, book &a) {
  if (a.x > b.x)
    return true;
  else if (a.x == b.x) {
    if (b.y == 1 && b.z == 1) {
      if (a.y == 0 || a.z == 0)
        return true;
      else
        return false;
    } else
      return false;
  } else
    return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, k;
  cin >> n >> k;
  vector<book> b;
  for (int i = 0; i < n; i++) {
    book tbook;
    cin >> tbook.x >> tbook.y >> tbook.z;
    b.push_back(tbook);
  }
  sort(b.begin(), b.end(), comp);
  int k1, k2;
  k1 = k2 = k;
  long long ans = 0LL;
  for (int i = 0; i < n; i++) {
    if (k1 <= 0 && k2 <= 0) break;
    if (b[i].y == 1 && b[i].z == 1) {
      k1--;
      k2--;
      ans += b[i].x;
    } else if (b[i].y == 1 && k1 > 0) {
      k1--;
      ans += b[i].x;
    } else if (b[i].z == 1 && k2 > 0) {
      k2--;
      ans += b[i].x;
    }
  }
  if (k1 <= 0 && k2 <= 0)
    cout << ans << "\n";
  else
    cout << -1 << "\n";
}
