#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int n, k;
  cin >> n >> k;
  vector<long long int> v;
  vector<long long int> v1;
  vector<long long int> v2;
  for (long long int i = 0; i < n; i++) {
    long long int t, a, b;
    cin >> t >> a >> b;
    if (a == 1 && b == 1) {
      v.push_back(t);
    } else if (a == 1) {
      v1.push_back(t);
    } else if (b == 1) {
      v2.push_back(t);
    }
  }
  if (v.size() + v1.size() < k || v.size() + v2.size() < k) {
    cout << "-1" << endl;
  } else {
    long long int p = 0;
    long long int p1 = 0;
    long long int p2 = 0;
    sort(v.begin(), v.end());
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());
    long long int m = 0;
    long long int time = 0;
    while (m != k) {
      if (p >= v.size()) {
        time += v1[p1] + v2[p2];
        p1 += 1;
        p2 += 1;
        m += 1;
      } else if (p1 >= v1.size() || p2 >= v2.size()) {
        time += v[p];
        p += 1;
        m += 1;
      } else if (v[p] <= v[p1] + v[p2]) {
        time += v[p];
        p += 1;
        m += 1;
      } else {
        time += v1[p1] + v2[p2];
        p1 += 1;
        p2 += 1;
        m += 1;
      }
    }
    cout << time << endl;
  }
  return 0;
}
