#include <bits/stdc++.h>
const int BIG = 1e5 + 55;
const int BIGG = 1e9 + 7;
const long long BIGGE = 1e12 + 55;
const double SML = (1e-7);
using namespace std;
long long n, k, sum;
vector<int> v, a, b;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n >> k;
  for (int i = 0; i < n; i++) {
    int x, y, z;
    cin >> x >> y >> z;
    if (y && z)
      v.push_back(x);
    else if (y)
      a.push_back(x);
    else if (z)
      b.push_back(x);
  }
  sort(v.begin(), v.end());
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  if (min(a.size(), b.size()) + v.size() >= k) {
    int l = 1, i = 0, x = 0;
    for (; i < a.size() && i < b.size(); l++) {
      if (x < v.size()) {
        if (v[x] < a[i] + b[i]) {
          sum += v[x];
          x++;
        } else {
          sum += a[i] + b[i];
          i++;
        }
      } else {
        sum += a[i] + b[i];
        i++;
      }
      if (l == k) break;
    }
    if (l == k)
      cout << sum;
    else {
      for (; l <= k; x++, l++) sum += v[x];
      cout << sum;
    }
  } else
    cout << -1;
  return 0;
}
