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

public class readingBooks {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(in.readLine());
        int N = Integer.parseInt(st.nextToken()), K = Integer.parseInt(st.nextToken()), totalTime = 0;

        int[][] books = new int[N][5];
        int[] alice = new int[N];
        int[] bob = new int[N];

        for(int i = 0; i < N; i++){
            st = new StringTokenizer(in.readLine());
            books[i][0] = Integer.parseInt(st.nextToken());
            books[i][1] = Integer.parseInt(st.nextToken());
            books[i][2] = Integer.parseInt(st.nextToken());
        }

        Arrays.sort(books, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        int amtA = 0, amtB = 0;
        for(int[] book : books){
            if(book[1] == 1 && amtA < K) {
                alice[amtA++] = book[0];
                book[3] = 1;
            }
            if(book[2] == 1 && amtB < K) {
                bob[amtB++] = book[0];
                book[4] = 1;
            }
        }
        if(amtA < K || amtB < K){
            System.out.println(-1);
            System.exit(0);
        }


        while(amtA + amtB < N){
            if(amtA < amtB) {
                for (int[] book : books) {
                    if (book[3] == 0) {
                        alice[amtA++] += book[0];
                        break;
                    }
                }
            }
            else {
                for(int[] book : books) {
                    if(book[4] == 0){
                        bob[amtB++] += book[0];
                        break;
                    }
                }
            }
        }

        int timeA = 0, timeB = 0;
        for(int i : alice) timeA += i;
        for(int i : bob) timeB += i;
        System.out.println(Math.max(timeA, timeB));

    }
}
