#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<long long int, long long int> &a,
               const pair<long long int, long long int> &b) {
  return (a.second < b.second);
}
int32_t main() {
  long long int t = 1;
  while (t--) {
    long long int n, k;
    cin >> n >> k;
    vector<long long int> x;
    vector<long long int> y;
    vector<long long int> z;
    for (long long int i = 0; i < n; i++) {
      long long int a, b, c;
      cin >> a >> b >> c;
      if (b == 1 && c == 1) {
        x.push_back(a);
      } else if (b == 1) {
        y.push_back(a);
      } else
        z.push_back(a);
    }
    if (x.size() + min(y.size(), z.size()) < k)
      cout << "-1" << endl;
    else {
      sort(x.begin(), x.end());
      sort(y.begin(), y.end());
      sort(z.begin(), z.end());
      long long int ans = 0, in = 0, ch = k - 1;
      if (x.size() < k) {
        for (long long int i = 0; i < k - x.size(); i++) ans += (y[i] + z[i]);
        ch = x.size() - 1;
        in = k - x.size();
      }
      for (long long int i = in; i < min(z.size(), y.size()) && ch >= 0; i++) {
        if (y[i] + z[i] <= x[ch]) {
          ans += y[i] + z[i];
          ch--;
        } else
          break;
      }
      for (long long int i = 0; i <= ch; i++) ans += x[i];
      cout << ans << endl;
    }
  }
}
