#include <bits/stdc++.h>
using namespace std;
vector<long long> v1, va, vb;
vector<pair<long long, char> > v;
bool cmp(pair<long long, char> a, pair<long long, char> b) {
  if (a.second == 'c' && b.second == 'c') return (a.first < b.first);
  if (b.second == 'c') return (0);
  if (a.second == 'c') return (1);
  return (a.first < b.first);
}
int main() {
  long long n, k;
  scanf("%lld", &n);
  scanf("%lld", &k);
  long long i, j, l;
  for (i = 0; i < n; i++) {
    long long t, a, b;
    scanf("%lld", &t);
    scanf("%lld", &a);
    scanf("%lld", &b);
    if (a == 1 && b == 1) {
      v1.push_back(t);
    } else if (a == 1) {
      va.push_back(t);
    } else if (b == 1) {
      vb.push_back(t);
    }
  }
  l = min(min(va.size(), vb.size()), v1.size());
  long long ans = 0, a = 0, b = 0;
  for (i = 0; i < l; i++) {
    if (va[i] + vb[i] < v1[i]) {
      ans += (va[i] + vb[i]);
      v.push_back({v1[i], 'c'});
    } else {
      ans += v1[i];
      v.push_back({va[i], 'a'});
      v.push_back({vb[i], 'b'});
    }
    a++;
    b++;
  }
  for (i = l; i < v1.size(); i++) {
    v.push_back({v1[i], 'c'});
  }
  for (i = l; i < va.size(); i++) {
    v.push_back({va[i], 'a'});
  }
  for (i = l; i < vb.size(); i++) {
    v.push_back({vb[i], 'b'});
  }
  if (a >= k && b >= k) {
    cout << ans;
    return 0;
  }
  sort(v.begin(), v.end(), cmp);
  for (i = 0; i < v.size(); i++) {
    if (v[i].second == 'a') {
      if (a < k) {
        ans += v[i].first;
        a++;
      }
    }
    if (v[i].second == 'b') {
      if (b < k) {
        ans += v[i].first;
        b++;
      }
    }
    if (v[i].second == 'c') {
      if (a < k || b < k) {
        ans += v[i].first;
        a++;
        b++;
      }
    }
  }
  if (a >= k && b >= k)
    printf("%lld\n", ans);
  else
    cout << "-1\n";
  return 0;
}
