#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long inf = 2e18 + 5;
void solve() {
  long long n, k;
  cin >> n >> k;
  vector<pair<long long, pair<long long, long long> > > a(n);
  vector<long long> alice, bob;
  long long x, y, z;
  for (long long i = (0); i < (n); i++) {
    cin >> x >> y >> z;
    a[i].first = x;
    a[i].second.first = y;
    a[i].second.second = z;
  }
  sort(a.begin(), a.end());
  long long sum = 0, al = 0, bo = 0;
  for (long long i = (0); i < (n); i++) {
    if (a[i].second.first == 1 && a[i].second.second == 1) {
      al++;
      bo++;
      sum += a[i].first;
    } else if (a[i].second.first == 1) {
      alice.push_back(a[i].first);
      sum += a[i].first;
      al++;
    } else if (a[i].second.second == 1) {
      bob.push_back(a[i].first);
      sum += a[i].first;
      bo++;
    }
    if (al >= k && bo >= k) break;
  }
  if (al < k || bo < k) {
    cout << -1 << endl;
    return;
  }
  for (long long i = (long long)alice.size() - 1; i >= 0, al > k; i--, al--)
    sum -= alice[i];
  for (long long i = (long long)bob.size() - 1; i >= 0, bo > k; i--, bo--)
    sum -= bob[i];
  cout << sum << endl;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long cases = 1;
  for (long long iter = 0; iter < cases; iter++) {
    solve();
  }
  return 0;
}
