#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, k;
  cin >> n >> k;
  long long t, a, b;
  long long alice[n], count1 = 0;
  long long bob[n], count2 = 0;
  long long both[n], count3 = 0;
  long long min = 0;
  long long count;
  long long x = 0, y, z;
  for (int i = 0; i < n; i++) {
    cin >> t >> a >> b;
    if (a && b) {
      both[count3++] = t;
    } else if (a) {
      alice[count1++] = t;
    } else if (b) {
      bob[count2++] = t;
    }
  }
  sort(alice, alice + count1);
  sort(bob, bob + count2);
  sort(both, both + count3);
  while (x < k && x < count3) {
    min += both[x];
    x++;
  }
  y = x;
  count = x;
  x = 0;
  while (count < k && x < count1 && x < count2) {
    min += alice[x];
    min += bob[x];
    x++;
    count++;
  }
  if (count < k) {
    cout << -1 << '\n';
  } else {
    y--;
    while (y >= 0 && x < count1 && x < count2) {
      if (both[y] <= (alice[x] + bob[x])) {
        min -= both[y];
        min += (alice[x] + bob[x]);
        x++;
        y--;
      } else {
        break;
      }
    }
    cout << min << '\n';
  }
  return 0;
}
