#include <bits/stdc++.h>
using namespace std;
const string YESNO[2] = {"NO", "YES"};
const string YesNo[2] = {"No", "Yes"};
const string yesno[2] = {"no", "yes"};
void YES(bool t = 1) { cout << YESNO[t] << "\n"; }
void Yes(bool t = 1) { cout << YesNo[t] << "\n"; }
void yes(bool t = 1) { cout << yesno[t] << "\n"; }
const long long mod = 1e9 + 7;
const long long mxN = 2e6 + 5;
long long n, m, x, y;
array<long long, 3> a[mxN];
string s, t;
void code() {
  cin >> n >> m;
  vector<long long> v1, v2, v3;
  for (long long i = 0; i < n; i++) {
    a[i][0] = a[i][1] = a[i][2] = 0;
    cin >> a[i][0] >> a[i][1] >> a[i][2];
    if (a[i][1] == 1 && a[i][2] == 1) {
      v1.push_back(a[i][0]);
    }
    if (a[i][1] == 1 && a[i][2] == 0) {
      v2.push_back(a[i][0]);
    }
    if (a[i][1] == 0 && a[i][2] == 1) {
      v3.push_back(a[i][0]);
    }
  }
  sort(v1.begin(), v1.end());
  sort(v2.begin(), v2.end());
  sort(v3.begin(), v3.end());
  long long ans = 0;
  long long k = 0;
  long long i = 0, j = 0;
  long long x = v1.size(), y = v2.size(), z = v3.size();
  while (k <= m && i < x && j < min(y, z)) {
    k++;
    if (v1[i] <= v2[j] + v3[j]) {
      ans += v1[i];
      i++;
    } else {
      ans += (v2[j] + v3[j]);
      j++;
    }
  }
  while (k <= m && i < x) {
    ans += v1[i];
    i++;
    k++;
  }
  while (k <= m && j < min(y, z)) {
    ans += v2[j] + v3[j];
    k++;
    j++;
  }
  if (k < m)
    cout << -1 << "\n";
  else
    cout << ans << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t = 1;
  while (t--) code();
}
