#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t = 1, i, j, k;
  for (long long ii = 1; ii <= t; ii++) {
    long long n, m;
    cin >> n >> m;
    vector<long long> a, b, c, ta(n), tb(n), tc(n);
    for (i = 0; i < n; i++) cin >> ta[i] >> tb[i] >> tc[i];
    for (i = 0; i < n; i++) {
      if (tb[i] == 1) {
        if (tc[i] == 1)
          a.push_back(ta[i]);
        else
          b.push_back(ta[i]);
      } else if (ta[i] == 1)
        c.push_back(ta[i]);
    }
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    sort(c.begin(), c.end());
    long long ans = 0;
    for (i = 0; i < min(m, (long long)a.size()); i++) ans += a[i];
    k = i;
    for (j = 0; j < b.size() && k < m; j++, k++) ans += b[j];
    if (k < m) {
      cout << "-1" << '\n';
      continue;
    }
    k = i;
    for (j = 0; j < c.size() && k < m; j++, k++) ans += c[j];
    if (k < m) {
      cout << "-1" << '\n';
      continue;
    }
    cout << ans << '\n';
  }
  return 0;
}
