#include <bits/stdc++.h>
using namespace std;
bool comp(pair<long long int, long long int> a,
          pair<long long int, long long int> b) {
  if (a.first == b.first) return a.first < b.first;
  return a.first < b.first;
}
int main() {
  long long int n, k;
  cin >> n >> k;
  long long int t[n];
  bool a[n], b[n];
  vector<pair<long long int, long long int>> v;
  for (long long int i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
    v.push_back({t[i], i});
  }
  sort(v.begin(), v.end(), comp);
  deque<long long int> s1, s2;
  long long int ans = 0;
  for (long long int i = 0; i < n; i++) {
    if (k == 0) break;
    long long int idx = v[i].second;
    if (a[idx] == 1 && b[idx] == 1) {
      ans += v[i].first;
      k--;
    } else {
      if (a[idx] == 0) {
        s1.push_back(v[i].first);
      } else if (b[idx] == 0) {
        s2.push_back(v[i].first);
      } else {
        s1.push_back(v[i].first);
        s2.push_back(v[i].first);
      }
      if (s1.size() >= 1 && s2.size() >= 1) {
        ans += (s1[0] + s2[0]);
        s1.pop_front();
        s2.pop_front();
        k--;
      }
    }
  }
  if (k > 0)
    cout << -1 << "\n";
  else
    cout << ans << "\n";
}
