#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k;
  int *lastA, *lastB;
  cin >> n >> k;
  lastA = new int[200001];
  lastB = new int[200001];
  int **arr = new int *[10001];
  for (int i = 0; i <= 10000; i++) {
    arr[i] = new int[3];
    arr[i][0] = 0;
    arr[i][1] = 0;
    arr[i][2] = 0;
  }
  for (int i = 0; i <= 200000; i++) {
    lastA[i] = 10001;
    lastB[i] = 10001;
  }
  for (int i = 0; i < n; i++) {
    int pos, a, b;
    cin >> pos >> a >> b;
    if (!(a || b)) {
      continue;
    }
    if (a && b)
      arr[pos][2]++;
    else if (a)
      arr[pos][1]++;
    else if (b)
      arr[pos][0]++;
  }
  int countA = 0;
  int countB = 0;
  int time = 0;
  int k1, k2;
  k1 = k2 = k;
  int a = 0;
  int b = 0;
  for (; a <= 10000; a++) {
    while ((k1 > 0) && (arr[a][1] || arr[a][2])) {
      k1--;
      time += a;
      if ((arr[a][2])) {
        k2--;
        arr[a][2]--;
      } else if (arr[a][1]) {
        arr[a][1]--;
        lastA[countA++] = a;
      }
    }
    if (k1 == 0) {
      break;
    }
  }
  if (k1 > 0) {
    cout << -1;
    return 0;
  }
  countB = 0;
  for (; b <= 10000; b++) {
    if (k2 == 0) {
      break;
    }
    while ((k2 > 0) && (arr[b][0] || arr[b][2])) {
      k2--;
      if (arr[b][2]) {
        time = time - lastA[countA - 1] + b;
        arr[b][2]--;
        countA--;
      } else if (arr[b][0]) {
        lastB[countB++] = b;
        time += b;
        arr[b][0]--;
      }
    }
  }
  if (k2 > 0) {
    cout << -1;
    return 0;
  }
  int i = (a > b) ? a : b;
  for (; i <= 10000; i++) {
    while (arr[i][2] && countA > 0 && countB > 0) {
      if (lastA[countA - 1] + lastB[countB - 1] - i > 0) {
        time = time - lastA[countA - 1] - lastB[countB - 1] + i;
        countA--;
        countB--;
        arr[i][2]--;
      } else {
        cout << time;
        return 0;
      }
    }
  }
  cout << time;
  return 0;
}
