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

public class Main {

    private static long testCase(int n, int k, PriorityQueue<Integer> books) {
        long ans = 0;

        for (int i = 0; i < k; i++) {
            if (books.isEmpty()) {
                return -1;
            } else {
                ans += books.poll();
            }
        }


        return ans;
    }

    public static void main(String[] args) {
        FastScanner in = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        //int t = in.nextInt();  // Scanner has functions to read ints, longs, strings, chars, etc.
        //in.nextLine();
        //for (int i = 1; i <= t; ++i) {
        int n = in.nextInt(), k = in.nextInt();
        PriorityQueue<Integer> booksThatAliceLikes = new PriorityQueue<>(), booksThatBobLikes = new PriorityQueue<>();
        PriorityQueue<Integer> books = new PriorityQueue<>();
        //int[][] books = new int[n][3];

        for (int i = 0; i < n; i++) {
            int[] book = {in.nextInt(), in.nextInt(), in.nextInt()};
            if (book[1] == 1 && book[2] == 1) {
                books.offer(book[0]);
            } else if (book[1] == 1 && book[2] == 0) {
                if (booksThatBobLikes.isEmpty()) {
                    booksThatAliceLikes.offer(book[0]);
                } else {
                    books.offer(booksThatBobLikes.poll() + book[0]);
                }
            } else if (book[1] == 0 && book[2] == 1) {
                if (booksThatAliceLikes.isEmpty()) {
                    booksThatBobLikes.offer(book[0]);
                } else {
                    books.offer(booksThatAliceLikes.poll() + book[0]);
                }
            }
        }

        out.println(testCase(n, k, books));
        //}

        out.close();
    }

    private static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");
        String next() {
            while (!st.hasMoreTokens())
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] readArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = nextInt();
            return a;
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }
}