import java.io.*;
import java.util.*;
public class E1374{
    static BufferedReader br;
    static PrintWriter out;
    static StringBuilder sb;
    public static void main(String args[]) throws IOException{
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        sb = new StringBuilder("");
        int t = 1;
        while(t-->0){
            solve();
        }
        out.print(sb);
        out.flush();
    }
    public static void solve() throws IOException{
        StringTokenizer str = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(str.nextToken());
        int k = Integer.parseInt(str.nextToken());

        int temp_n = n;
        TreeSet<Integer> both = new TreeSet<>();
        TreeSet<Integer> AliceSet = new TreeSet<>();
        TreeSet<Integer> BobSet = new TreeSet<>();

        int sum = 0;
        int ans = 0;
        while(temp_n-->0){
            str = new StringTokenizer(br.readLine());
            int time = Integer.parseInt(str.nextToken());
            int a = Integer.parseInt(str.nextToken());
            int b = Integer.parseInt(str.nextToken());

            if(a==0 && b==0)
                continue;
            else if(a==1 && b==1){
                both.add(time);
                sum+=time;
            }else if(a==1 && b==0){
                AliceSet.add(time);
            }else{
                BobSet.add(time);
            }
        }

        if(k>both.size()){
            ans = sum;
            k-= both.size();
        }else{
            for(int i: both){
                // System.out.println(i);
                ans+= i;
                k--;
                if(k==0)
                break;
            }
        }

        // System.out.println("Remaining k = "+ k+" sum="+ans);


        boolean flag = true;
        int temp_k = k;
        xt:
        if(k>0){
            if(AliceSet.size()>=k){
                // System.out.println("ALICE");
                for(int i: AliceSet){
                    // System.out.println(i);
                    ans+= i;
                    temp_k--;
                    if(temp_k==0)
                        break;
                }
            }else{
                flag = false;
                break xt;
            }

            if(BobSet.size()>=k){
                // System.out.println("BOB");
                for(int i: BobSet){
                    // System.out.println(i);
                    ans+= i;
                    k--;
                    if(k==0)
                        break;
                }
            }else{
                flag = false;
                break xt;
            }
        }

        if(flag)
            sb.append(ans);
        else
            sb.append("-1");
    }
}