#include <bits/stdc++.h>
char local = 'O';
using namespace std;
class str {
 public:
  int a;
  int b;
  int c;
};
bool operator<(const str p1, const str p2) { return p1.a > p2.a; }
int main() {
  char local = 'L';
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n, k;
  cin >> n >> k;
  int c1 = 0, b1 = 0;
  vector<str> S;
  for (long long i = 0; i < n; i++) {
    long long aa, bb, cc;
    cin >> aa >> bb >> cc;
    if (bb == 1 || cc == 1) {
      str p;
      p.a = aa;
      p.b = bb;
      p.c = cc;
      S.push_back(p);
    }
    if (cc) c1++;
    if (bb) b1++;
  }
  if (c1 < k || b1 < k)
    cout << "-1\n";
  else {
    sort(S.begin(), S.end());
    for (long long i = 0; i < S.size(); i++) {
      if (S[i].b == 1 && S[i].c == 1 && c1 > k && b1 > k) {
        S[i].a = 0;
        c1--;
        b1--;
      } else if (S[i].c == 1 && c1 > k && S[i].b == 0) {
        S[i].a = 0;
        c1--;
      } else if (S[i].b == 1 && b1 > k && S[i].c == 0) {
        S[i].a = 0;
        b1--;
      }
    }
    long long ans = 0;
    for (long long i = 0; i < S.size(); i++) ans += S[i].a;
    cout << ans << "\n";
  }
  return 0;
}
