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

public class Main
{  
    public static void main(String[] args) throws IOException 
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());
        
        ArrayList<Integer> setAB = new ArrayList<>();
        ArrayList<Integer> setA = new ArrayList<>();
        ArrayList<Integer> setB = new ArrayList<>();
        
        ArrayList<Integer> sumAB = new ArrayList<>();
        ArrayList<Integer> sumA = new ArrayList<>();
        ArrayList<Integer> sumB = new ArrayList<>();
        
        for(int i=0; i<n; i++)
        {
            st = new StringTokenizer(br.readLine());
            int time = Integer.parseInt(st.nextToken());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            
            if(a == 1 && b == 1) setAB.add(time);
            else if(a == 1) setA.add(time);
            else setB.add(time);
        }
        
        Collections.sort(setA);
        Collections.sort(setB);
        Collections.sort(setAB);
        
        sumA.add(0);
        for(int i=0; i<setA.size(); i++) sumA.add(setA.get(i) + sumA.get(i));
        
        sumAB.add(0);
        for(int i=0; i<setAB.size(); i++) sumAB.add(setAB.get(i) + sumAB.get(i));
        
        sumB.add(0);
        for(int i=0; i<setB.size(); i++) sumB.add(setB.get(i) + sumB.get(i));
        
        int ans = Integer.MAX_VALUE;
        for (int cnt = 0; cnt < Math.min(k + 1, sumAB.size()); cnt++) {
    		if (k - cnt < sumA.size() && k - cnt < sumB.size())
    			ans = Math.min(ans, sumAB.get(cnt) + sumA.get(k - cnt) + sumB.get(k - cnt));
    	}
	
	    if (ans == Integer.MAX_VALUE) ans = -1;
	    System.out.println(ans);
	}
}