#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
void solve() {
  long long n, k;
  cin >> n >> k;
  long long a[n + 1], b[n + 1];
  set<long long> x, y, z;
  for (int i = 1; i <= n; i++) {
    long long t;
    cin >> t;
    cin >> a[i] >> b[i];
    if (a[i] == b[i] and b[i] == 1)
      z.insert(t);
    else if (a[i] == 1)
      x.insert(t);
    else if (b[i] == 1)
      y.insert(t);
  }
  long long cnt1 = 0, cnt2 = 0;
  long long ans = 0;
  if (((int)(x).size()) + ((int)(z).size()) < k or
      ((int)(y).size()) + ((int)(z).size()) < k) {
    cout << -1;
    return;
  }
  while (cnt1 < k or cnt2 < k) {
    if (z.empty()) {
      while (cnt1 < k) {
        for (auto i : x) {
          ans += i;
          cnt1++;
          if (cnt1 == k) break;
        }
      }
      while (cnt2 < k) {
        for (auto i : y) {
          ans += i;
          cnt2++;
          if (cnt2 == k) break;
        }
      }
      cout << ans;
      return;
    } else if (x.empty()) {
      while (cnt1 < k) {
        ans += (*z.begin());
        z.erase(z.begin());
        cnt1++;
        cnt2++;
      }
      while (cnt2 < k) {
        if (z.empty() or *y.begin() < *z.begin()) {
          ans += (*y.begin());
          y.erase(y.begin());
          cnt2++;
        } else if (!z.empty()) {
          ans += (*z.begin());
          z.erase(z.begin());
          cnt2++;
          cnt1++;
        }
      }
      cout << ans;
      return;
    } else if (y.empty()) {
      while (cnt2 < k) {
        ans += (*z.begin());
        z.erase(z.begin());
        cnt1++;
        cnt2++;
      }
      while (cnt1 < k) {
        if (z.empty() or *x.begin() < *z.begin()) {
          ans += (*x.begin());
          x.erase(x.begin());
          cnt1++;
        } else if (!z.empty()) {
          ans += (*z.begin());
          z.erase(z.begin());
          cnt2++;
          cnt1++;
        }
      }
      cout << ans;
      return;
    } else {
      if ((*x.begin() + *y.begin()) < *z.begin()) {
        ans += (*x.begin() + *y.begin());
        x.erase(x.begin());
        y.erase(y.begin());
        cnt1++;
        cnt2++;
      } else {
        ans += (*z.begin());
        z.erase(z.begin());
        cnt1++;
        cnt2++;
      }
    }
  }
  cout << ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  solve();
}
