#include <bits/stdc++.h>
using namespace std;
long long int n, m;
void solve() {
  cin >> n;
  vector<long long int> both, alice, bob;
  long long int z;
  cin >> m;
  z = m;
  long long int t, x, y;
  for (long long int i = 0; i < n; i++) {
    cin >> t >> x >> y;
    if (x && y)
      both.push_back(t);
    else if (x && !y)
      alice.push_back(t);
    else if (!x && y)
      bob.push_back(t);
  }
  sort(both.begin(), both.end());
  sort(alice.begin(), alice.end());
  sort(bob.begin(), bob.end());
  long long int ans = 0;
  long long int i = 0, j = 0, k = 0;
  while (i < both.size() && j < alice.size() && k < bob.size()) {
    if (alice[j] + bob[k] <= both[i]) {
      ans += alice[j] + bob[k];
      j++;
      k++;
      m--;
    } else {
      ans += both[i];
      i++;
      m--;
    }
    if (m == 0) break;
  }
  if (m == 0) {
    cout << ans << "\n";
    return;
  }
  if (i == both.size()) {
    while (m--) {
      ans += alice[j] + bob[k];
      j++;
      k++;
    }
    if (j > alice.size() || k > bob.size()) ans = -1;
  } else if (j == alice.size()) {
    if (z <= both.size()) {
      ans = 0;
      for (auto x : both) {
        ans += x;
        z--;
        if (z == 0) break;
      }
    } else {
      ans = -1;
    }
  } else if (k == bob.size()) {
    if (z <= both.size()) {
      ans = 0;
      for (auto x : both) {
        ans += x;
        z--;
        if (z == 0) break;
      }
    } else {
      ans = -1;
    }
  }
  cout << ans << "\n";
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  solve();
  return 0;
}
