import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;

// import java.text.DecimalFormat; 
// import java.text.DecimalFormatSymbols; 
 
 
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
 
public class TestClass {
    public static void main(String args[] ) throws Exception {
        /* Sample code to perform I/O:
         * Use either of these methods for input
 
        //BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String name = br.readLine();                // Reading input from STDIN
        System.out.println("Hi, " + name + ".");    // Writing output to STDOUT
 
        //Scanner
        Scanner s = new Scanner(System.in);
        String name = s.nextLine();                 // Reading input from STDIN
        System.out.println("Hi, " + name + ".");    // Writing output to STDOUT
        
        for Round off
         DecimalFormat deciFormat = new DecimalFormat(); 
        deciFormat.setMaximumFractionDigits(9); 
        */
 
        // Write your code here
        StringBuffer str = new StringBuffer();
        PrintWriter pw=new PrintWriter(System.out);
        Scanner scn=new Scanner(System.in);    

        int n = scn.nextInt();
        int k = scn.nextInt();
        Queue<Integer> com =new PriorityQueue<Integer>();
        Queue<Integer> al =new PriorityQueue<Integer>();
        Queue<Integer> bo =new PriorityQueue<Integer>();
        while(n-->0){
            int t,a,b;
            t = scn.nextInt();
            a = scn.nextInt();
            b = scn.nextInt();
            if(a==1&&b==1)
                com.add(t);
            else if(a==1)
                al.add(a);
            else if(b==1)
                bo.add(b);
        }
        int res=0;
        for(int i=0;i<k;i++){
            if((al.isEmpty()||bo.isEmpty())&&com.isEmpty()){
                res=-1;
                break;
            } 
            if(al.isEmpty()||bo.isEmpty()||!com.isEmpty()&&com.peek()<al.peek()+bo.peek())
                res+=com.poll();
            else 
                res+=al.poll()+bo.poll();
        }
        str.append(res+"\n");
        pw.println(str.toString());
        
        pw.close();
    }
    public static List<Integer> prime(){
        List<Integer> li = new ArrayList<Integer>();
        int N = 100000;
        li.add(1);
        int[] pr = new int[N+1];
        for(int i=2;i<=N;++i){
            if(pr[i]==0){
                pr[i]=i;
                li.add(i);
            }
            for(int j=0;j<li.size()&&li.get(j)<=pr[i]&&i*li.get(j)<=N;++j)
                pr[i*li.get(j)]=li.get(j);
        }
        return li;
    }
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
    
}