import java.io.*;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class ReadingBooks_1600 {
    public static void main(String[] args) {
        MyScanner sc = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        int N = Integer.parseInt(sc.next());
        int K = Integer.parseInt(sc.next());
        TreeSet<Integer> bothLike = new TreeSet<>();
        TreeSet<Integer> aliceLikes = new TreeSet<>();
        TreeSet<Integer> bobLikes = new TreeSet<>();
        for(int i = 0; i < N; i++) {
            int time = Integer.parseInt(sc.next());
            int alice = Integer.parseInt(sc.next());
            int bob = Integer.parseInt(sc.next());
            if(alice == 1 && bob == 1) bothLike.add(time);
            else if(alice == 1 && bob == 0) aliceLikes.add(time);
            else if(alice == 0 && bob == 1) bobLikes.add(time);
        }
        int result = 0;
        int needed = K - bothLike.size();
        if(needed > Math.min(aliceLikes.size(), bobLikes.size())) {
            System.out.println(-1);
            return;
        }
        if(needed <= 0) {
            for(int i = 0; i < K; i++) {
                result += bothLike.first();
                bothLike.remove(bothLike.first());
            }
            System.out.println(result);
        } else {
            for(int i = 0; i < bothLike.size(); i++) {
                result += bothLike.first();
                bothLike.remove(bothLike.first());
            }
            for(int i = 0; i < needed; i++) {
                result += aliceLikes.first();
                aliceLikes.remove(aliceLikes.first());
                result += bobLikes.first();
                bobLikes.remove(bobLikes.first());
            }
            System.out.println(result);
        }
        out.close();
    }


    public static PrintWriter out;

    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

    }
}


