#include <bits/stdc++.h>
using namespace std;
const long long M = 1e9 + 7;
const long long N = 2e6 + 10;
const long long IM = 1e15 + 37;
const long double PI = 3.1415926535897932384;
void PV(vector<long long> v) {
  for (long long i = 0; i < v.size(); i++) cout << v[i] << " ";
  cout << "\n";
}
void PVV(vector<pair<long long, long long>> v) {
  for (long long i = 0; i < v.size(); i++)
    cout << v[i].first << " " << v[i].second << "\n";
}
void PA(long long v[], long long n, long long x = 0) {
  for (long long i = x; i < n + x; i++) cout << v[i] << ' ';
  cout << "\n";
}
void IN(long long a[], long long n, long long x = 0) {
  for (long long i = x; i < n + x; i++) cin >> a[i];
}
inline void PP(long long n) { cout << n << " "; }
inline void PP(long long n, long long m) { cout << n << " " << m << "\n"; }
inline void PP(long long n, long long m, long long q) {
  cout << n << " " << m << " " << q << "\n";
}
inline void PP(long long n, long long m, long long q, long long u) {
  cout << n << " " << m << " " << q << " " << u << "\n";
}
inline void op() {}
signed main() {
  op();
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long i, j, x, y, u, l;
  {
    i = j = x = y = u = l = 0;
    vector<tuple<long long, long long, long long>> v;
    long long n, k;
    cin >> n >> k;
    for (i = 0; i < n; i++) {
      cin >> l >> x >> y;
      v.push_back({l, x, y});
    }
    sort(v.begin(), v.end());
    x = k, y = k;
    long long a, b, c;
    l = 0;
    multiset<long long> sa, sb;
    for (i = 0; i < v.size(); i++) {
      a = get<0>(v[i]);
      b = get<1>(v[i]);
      c = get<2>(v[i]);
      if (b && c) {
        if (x || y) l += a;
        if (x == 0 && y == 0 && sa.size() > 0 && sb.size() > 0) {
          auto it = prev(sa.end());
          long long aa = *it;
          auto iit = prev(sb.end());
          long long bb = *iit;
          if (aa + bb > a) {
            l -= aa;
            l -= bb;
            l += a;
            sa.erase(*it);
            sb.erase(*iit);
          }
        }
        if (x == 0 && sa.size() > 0 && y) {
          auto it = prev(sa.end());
          l -= *it;
          sa.erase(it);
        }
        if (y == 0 && sb.size() > 0 && x) {
          auto it = prev(sb.end());
          l -= *it;
          sb.erase(it);
        }
        if (x) x--;
        if (y) y--;
      } else if (x && b) {
        x--;
        sa.insert(a);
        l += a;
      } else if (y && c) {
        y--;
        sb.insert(a);
        l += a;
      }
    }
    if (x || y) {
      cout << (-1) << "\n";
    } else
      cout << (l) << "\n";
  }
  return 0;
}
