#include <bits/stdc++.h>
using namespace std;
const long double PI = atan(1.0) * 4;
const int64_t INF = 3e18;
const int32_t LOG = 21;
const int32_t MOD = 1e9 + 7;
vector<long long int> v[3];
int32_t main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  long long int tests = 1;
  for (long long int ii = 0; ii < tests; ii++) {
    long long int n, k;
    cin >> n >> k;
    long long int ans = 0;
    for (long long int i = 0; i < n; i++) {
      long long int t, a, b;
      cin >> t >> a >> b;
      ans += t;
      if (a == 0 && b == 0) continue;
      if (a == 1 && b == 1) {
        v[2].push_back(t);
      } else if (a == 1 && b == 0)
        v[0].push_back(t);
      else if (b == 1 && a == 0)
        v[1].push_back(t);
    }
    long long int siz0 = v[0].size(), siz1 = v[1].size(), siz2 = v[2].size();
    if (siz2 + siz1 < k || siz2 + siz0 < k) {
      cout << -1 << '\n';
      return 0;
    }
    for (long long int i = 0; i < 3; i++) sort(v[i].begin(), v[i].end());
    for (long long int i = 0; i < 3; i++) {
      for (long long int j = 1; j < v[i].size(); j++) v[i][j] += v[i][j - 1];
    }
    if (siz0 > k && siz1 > k) {
      ans = min(ans, v[0][k - 1] + v[1][k - 1]);
    }
    for (long long int it = 0; it < v[2].size(); it++) {
      long long int rem = k - it - 1;
      if (rem <= 0) {
        ans = min(ans, v[2][it]);
        continue;
      }
      if (rem <= siz0 && rem <= siz1)
        ans = min(ans, v[0][rem - 1] + v[1][rem - 1] + v[2][it]);
    }
    cout << ans << '\n';
  }
  return 0;
}
