import java.util.*;
import java.io.*;

public class E {

  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] strs = br.readLine().split("\\s+");
    int n = Integer.parseInt(strs[0]);
    int k = Integer.parseInt(strs[1]);
    List<Integer> bothLike = new ArrayList<>();
    List<Integer> aliceLike = new ArrayList<>();
    List<Integer> bobLike = new ArrayList<>();
    int aliceCount = 0;
    int bobCount = 0;
    for (int i = 0; i < n; i++) {
      strs = br.readLine().split("\\s+");
      int t = Integer.parseInt(strs[0]);
      int a = Integer.parseInt(strs[1]);
      int b = Integer.parseInt(strs[2]);
      if (a == 1 && b == 1) {
        aliceCount++;
        bobCount++;
        bothLike.add(t);
      }
      else if (a == 1 && b == 0) {
        aliceCount++;
        aliceLike.add(t);
      }
      else if (a == 0 && b == 1) {
        bobCount++;
        bobLike.add(t);
      }
    }
    if (aliceCount < k || bobCount < k) {
      System.out.println(-1);
    }
    else {
      Collections.sort(bothLike);
      Collections.sort(aliceLike);
      Collections.sort(bobLike);
      int x = 0, y = 0, z = 0;
      int count = 0;
      int sum = 0;
      while (count < k && ((x < aliceLike.size() && y < bobLike.size()) || z < bothLike.size())) {
        if (x < aliceLike.size() && y < bobLike.size() && z < bothLike.size()) {
          if (aliceLike.get(x) + bobLike.get(y) <= bothLike.get(z)) {
            sum += aliceLike.get(x++) + bobLike.get(y++);
            count += 2;
          }
          else {
            sum += bothLike.get(z++);
            count++;
          }
        }
        else if (x < aliceLike.size() && y < bobLike.size() && z == bothLike.size()) {
          sum += aliceLike.get(x++) + bobLike.get(y++);
          count += 2;
        }
        else {
          sum += bothLike.get(z++);
          count++;
        }
      }
      System.out.println(sum);
    }
  }
}