#include <bits/stdc++.h>
using namespace std;
int s[200000];
int main() {
  long long ans = 0;
  int n, k, t[200000], a[200000], b[200000], i, count = 0;
  cin >> n >> k;
  for (i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
    if (a[i] == 1 && b[i] == 1) {
      s[count] = t[i];
      count++;
    }
  }
  int g = count, h = count;
  for (i = 0; i < n; i++) {
    if (a[i] == 1 && b[i] == 0) {
      s[count] = t[i];
      count++;
      g = count;
    }
  }
  count = h;
  for (i = 0; i < n; i++) {
    cin >> t[i] >> a[i] >> b[i];
    if (a[i] == 0 && b[i] == 1) {
      s[count] += t[i];
      count++;
    }
  }
  h = min(g, count);
  sort(s, s + h);
  if (h < k)
    cout << -1;
  else {
    for (i = 0; i < k; i++) ans += s[i];
    cout << ans;
  }
  return 0;
}
