#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n, k;
  cin >> n >> k;
  long long t[n], a[n], b[n];
  long long tot = 0;
  vector<long long> v, v1, v2;
  long long check1, check2 = 0;
  for (long long i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
    if (a[i] == b[i] && a[i] == 1) {
      v.push_back(t[i]);
      check1++;
      check2++;
    }
    if (a[i] == 1 && b[i] == 0) {
      v1.push_back(t[i]);
      check1++;
    }
    if (a[i] == 0 && b[i] == 1) {
      v2.push_back(t[i]);
      check2++;
    }
  }
  if (check1 < k || check2 < k) {
    cout << -1 << "\n";
    return 0;
  }
  if (k <= v.size()) {
    sort(v.begin(), v.end());
    for (long long i = 0; i < k; i++) {
      tot = tot + v[i];
    }
    cout << tot << "\n";
    return 0;
  } else {
    tot = 0;
    sort(v.begin(), v.end());
    for (long long i = 0; i < k && i < v.size(); i++) {
      tot = tot + v[i];
    }
    long long final = k;
    k = k - v.size();
    long long count1 = k;
    long long count2 = k;
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());
    long long i = 0;
    while (count1 < final && i < v1.size()) {
      tot = tot + v1[i];
      count1++;
      i++;
    }
    i = 0;
    while (count2 < final && i < v2.size()) {
      tot = tot + v2[i];
      i++;
      count2++;
    }
    cout << tot << "\n";
    return 0;
  }
}
