#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<int> both, a, b;
int ans = 2 * 1e9 + 1;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> k;
  both.push_back(0);
  a.push_back(0);
  b.push_back(0);
  for (int i = 1; i <= n; ++i) {
    int t, x, y;
    cin >> t >> x >> y;
    if (x && y)
      both.push_back(t);
    else if (x)
      a.push_back(t);
    else if (y)
      b.push_back(t);
  }
  sort(both.begin(), both.end());
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  int x = a.size(), y = b.size();
  for (int i = 1; i <= min(k, (int)both.size() - 1); ++i)
    both[i] += both[i - 1];
  for (int i = 1; i <= min(k, x - 1); ++i) a[i] += a[i - 1];
  for (int i = 1; i <= min(k, y - 1); ++i) b[i] += b[i - 1];
  for (int i = 0; i <= min(x - 1, y - 1); ++i)
    if (k - i <= both.size() - 1) ans = min(ans, both[k - i] + a[i] + b[i]);
  cout << ((ans == 2 * 1e9) ? (-1) : ans);
  return 0;
}
