import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;


public class ReadingBookseasyversion {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		ArrayList<Integer> both = new ArrayList<>();
		ArrayList<Integer> a    = new ArrayList<>();
		ArrayList<Integer> b    = new ArrayList<>();
		int bb = 0;
		int aa = 0;
		int bo = 0;
		for(int i=0;i<n;i++){
			int num = sc.nextInt();
			int x = sc.nextInt();
			int y = sc.nextInt();
			if(x == 1 && y == 1){
				both.add(num);
				bo++;
			}
			else if( x== 1 && y == 0){
				a.add(num);
				aa++;
			}
			else {
				b.add(num);
				bb++;
			}
		}
		if(bo+(Math.min(aa,bb))<k){
			System.out.println("-1");
		}
		else{
			long ans =0;
			Collections.sort(both);
			Collections.sort(a);
			Collections.sort(b);
			
			int i=0;int j =0;
			
			while(k-->0){
				if(i<both.size() && j<(Math.min(a.size(), b.size()))){
					if(both.get(i) < a.get(j)+b.get(j)){
						ans += a.get(j)+b.get(j);
						j++;
					}
					else{
						ans += both.get(i);
						i++;
					}
				}
				else if(i>=both.size()){
					ans += a.get(j)+b.get(j);
					j++;
				}
				else if(j>=(Math.min(a.size(), b.size()))){
					ans += both.get(i);
					i++;
				}
				
			}
			System.out.println(ans);
		}
	}

}
