#include <bits/stdc++.h>
using namespace std;
void fun() { ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); }
void solve() {
  fun();
  long long t = 1;
  while (t--) {
    long long n, k;
    cin >> n >> k;
    long long t[n], a[n], b[n];
    for (long long i = 0; i < n; i++) cin >> t[i] >> a[i] >> b[i];
    vector<long long> al, bl, bt;
    for (long long i = 0; i < n; i++) {
      if (a[i] && b[i])
        bt.push_back(t[i]);
      else if (a[i])
        al.push_back(t[i]);
      else if (b[i])
        bl.push_back(t[i]);
    }
    if (((al.size() + bt.size()) < k) || ((bl.size() + bt.size()) < k)) {
      cout << "-1\n";
      continue;
    }
    sort(al.begin(), al.end());
    sort(bl.begin(), bl.end());
    sort(bt.begin(), bt.end());
    set<long long> s;
    long long ca = 0, cb = 0, ans = 0, x = 0, z = 0;
    for (long long i = 0; i < min(k, (long long)bt.size()); i++)
      ans += bt[i], ca++, cb++;
    for (long long i = min((long long)(bt.size() - 1), k); i >= 0; i--) {
      if (x < al.size() && z < bl.size()) {
        long long v = al[x] + bl[z];
        if (v < bt[i]) {
          ans -= bt[i];
          ans += v;
          s.insert(bt[i]);
          x++, z++;
          continue;
        }
        if (v > bt[i]) break;
      }
    }
    for (long long i = x; i < x + (k - ca) && i < al.size() && i < bl.size();
         i++)
      ans += (al[i] + bl[i]), ca++;
    for (auto i : s) {
      if (ca < k)
        ans += i, ca++;
      else
        break;
    }
    cout << ans << "\n";
  }
}
signed main() {
  solve();
  return 0;
}
