#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n, k;
  cin >> n >> k;
  vector<pair<long long, long long>> v1, v2;
  vector<long long> v;
  for (long long i = 0; i < n; i++) {
    long long t1, a, b;
    cin >> t1 >> a >> b;
    if (a == 1) {
      if (b == 1)
        v1.push_back({t1, 1});
      else
        v1.push_back({t1, 2});
    } else if (b == 1) {
      v2.push_back({t1, a});
    }
  }
  if (v1.size() < k) {
    cout << "-1";
    return;
  }
  sort(v1.begin(), v1.end());
  long long t = 0, cnt = 0;
  for (long long i = 0; i < k; i++) {
    t += v1[i].first;
    if (v1[i].second == 1) cnt++;
  }
  if (cnt == k) {
    cout << t;
    return;
  }
  for (long long i = k; i < v1.size(); i++) {
    if (v1[i].second == 1) v.push_back(v1[i].first);
  }
  for (long long i = 0; i < v2.size(); i++) v.push_back(v2[i].first);
  sort(v.begin(), v.end());
  if (v.size() < k - cnt) {
    cout << "-1";
    return;
  }
  for (long long i = cnt; i < k; i++) {
    t += v[i - cnt];
  }
  cout << t;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  while (t--) {
    solve();
  }
}
