import java.util.Arrays;
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();
		int both[] = new int[n];
		int a[]    = new int[n];
		int b[]    = new int[n];
		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[bo++] = num;
			}
			else if( x== 1 && y == 0){
				a[aa++] = num;
			}
			else {
				b[bb++] = num;
			}
		}
		if(bo+aa+bb<k){
			System.out.println("-1");
		}
		else{
			long ans =0;
			Arrays.sort(both);
			Arrays.sort(a);
			Arrays.sort(b);
			bo = n-bo;
			aa = n-aa;
			bb = n-bb;
			
				for(int i=0;i<k;i++){
					if((bo<n && (aa<n && bb<n)) ){
						if((both[bo] <(a[aa]+b[bb]))){
							ans += a[aa++];
							ans += b[bb++];
//							System.out.println(ans+" "+1);
						}
					}
					else if(bo>=n && (aa>=n || bb>=n)){
						System.out.println("-1");
						System.exit(0);
					}
					else if(bo>=n && (aa<n || bb<n)){
						ans += a[aa++];
						ans += b[bb++];
//						System.out.println(ans+" 2");
					}
					else if(bo<n  && (aa>=n || bb>=n)){
						ans += both[bo++];
//						System.out.println(ans+" 3");
					}
				}
				System.out.println(ans);
		}
	}

}