#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, k;
  cin >> n >> k;
  long long a = 0, b = 0;
  long long t[n], A[n], B[n];
  vector<vector<long long>> v(n, vector<long long>(3, 0));
  vector<long long> equal;
  vector<long long> alice;
  vector<long long> bob;
  for (long long i = 0; i < n; i++) {
    cin >> t[i] >> A[i] >> B[i];
    v[i][0] = t[i];
    v[i][1] = A[i];
    v[i][2] = B[i];
    if (A[i] == 1) a++;
    if (B[i] == 1) b++;
    if (A[i] == 1 && B[i] == 1)
      equal.push_back(t[i]);
    else if (A[i] == 1)
      alice.push_back(t[i]);
    else if (B[i] == 1)
      bob.push_back(t[i]);
  }
  sort(equal.begin(), equal.end());
  sort(alice.begin(), alice.end());
  sort(bob.begin(), bob.end());
  if (a < k || b < k)
    cout << -1 << endl;
  else {
    sort(v.begin(), v.end());
    a = k;
    b = k;
    long long ans = 0;
    for (long long i = 0; i < n; i++) {
      if (a > 0 && b > 0 && v[i][1] == 1 && v[i][2] == 1) {
        ans += v[i][0];
        a--;
        b--;
        continue;
      }
      if (a > 0 && v[i][1] == 1) {
        ans += v[i][0];
        a--;
      }
      if (b > 0 && v[i][2] == 1) {
        ans += v[i][0];
        b--;
      }
    }
    long long ans1 = 0, a1 = k, b1 = k;
    long long sz = (long long)equal.size();
    for (long long j = 0; j < sz && a1 > 0 && b1 > 0; j++) {
      ans1 += equal[j];
      a1--;
      b1--;
    }
    for (long long j = 0; j < min((long long)alice.size(), a1); j++) {
      ans1 += alice[j];
    }
    for (long long j = 0; j < min((long long)alice.size(), b1); j++) {
      ans1 += bob[j];
    }
    cout << min(ans, ans1) << endl;
  }
  return 0;
}
