#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, m;
  cin >> n >> m;
  int c1 = 0, c2 = 0;
  vector<pair<int, pair<bool, bool>>> vp(n);
  for (int i = 0; i < n; i++) {
    int t;
    cin >> t;
    bool a, b;
    cin >> a >> b;
    vp[i].first = t;
    vp[i].second.first = a;
    vp[i].second.second = b;
  }
  sort(vp.begin(), vp.end());
  vector<int> a, b;
  int sum = 0;
  for (int i = 0; i < n; i++) {
    if (!vp[i].second.first && !vp[i].second.second) continue;
    if (vp[i].second.first && vp[i].second.second) {
      if (c1 < m) {
        sum += vp[i].first;
        c1++;
        if (c2 == m) {
          sum -= b.back();
          b.pop_back();
        } else
          c2++;
        if (c1 == m && c2 == m) break;
        continue;
      }
      sum += vp[i].first;
      c2++;
      sum -= a.back();
      a.pop_back();
      if (c1 == m && c2 == m) break;
      continue;
    }
    if (vp[i].second.first) {
      if (c1 == m) continue;
      c1++;
      sum += vp[i].first;
      a.push_back(vp[i].first);
    } else {
      if (c2 == m) continue;
      c2++;
      sum += vp[i].first;
      b.push_back(vp[i].first);
    }
    if (c1 == m && c2 == m) break;
  }
  if (c1 == m && c2 == m)
    cout << sum;
  else
    cout << -1;
  return 0;
}
