#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], b[mxN];
string s, t;
void code() {
  cin >> n >> m;
  for (long long i = 0; i < n; i++) {
    cin >> a[i][0] >> a[i][1] >> a[i][2];
  }
  sort(a, a + n, [](array<long long, 3> a, array<long long, 3> b) {
    if (a[1] + a[2] != b[1] + b[2]) {
      return a[1] + a[2] > b[1] + b[2];
    } else {
      return a[0] < b[0];
    }
  });
  long long ans = 0;
  long long k1 = 0, k2 = 0;
  for (long long i = 0; i < n; i++) {
    if (k1 >= m && k2 >= m) break;
    if (k1 >= m && a[i][2] == 0) continue;
    if (k2 >= m && a[i][1] == 0) continue;
    ans += a[i][0];
    k1 += (a[i][1] == 1);
    k2 += (a[i][2] == 1);
  }
  if (k1 >= m && k2 >= m)
    cout << ans << "\n";
  else
    cout << -1 << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t = 1;
  while (t--) code();
}
