import java.util.*;


public class Main {

	public static void main(String args[]) {
		int n = 0;
		int k = 0;
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		k = in.nextInt();
		PriorityQueue<Book> pq = new PriorityQueue<Book>(n, new BookComparator());
		int alice_count = 0;
		int bob_count = 0;
		
		for(int i=0;i<n;i++) {
			int t = in.nextInt();
			int a = in.nextInt();
			int b = in.nextInt();
			
			if(a == 1) {
				alice_count ++;
			}
			if(b == 1) {
				bob_count ++;
			}
			
			
			Book newBook = new Book(t,a,b);
			pq.add(newBook);
			
		}
		
		if(alice_count < k || bob_count<k) {
			System.out.println(-1);
			return;
		}
		alice_count = k;
		bob_count = k;
		long sum = 0;
		while(true) {
			if(alice_count == 0 && bob_count == 0)
				break;
//			System.out.println(alice_count+"     "+bob_count);
			Book tmp = pq.peek();
			if(tmp.a == 1) {
				alice_count --;
			}
			if(tmp.b == 1) {
				bob_count --;
			}
			tmp = pq.poll();
//			tmp.print();
			sum += tmp.time;
		}
		System.out.println(sum);
	}
	
}


class Book {
	public int time;
	public int a;
	public int b;
	public Book(int t,int p_a,int p_b) {
		time = t;
		a = p_a;
		b = p_b;
	}
	public void print() {
		System.out.println(time+"    "+a+"     "+b);
	}
}

class BookComparator implements Comparator<Book>{
	public int compare(Book first,Book second) {
        if(first.a == 1 && first.b == 1 && second.a == 1 && second.b == 1 && first.time<second.time)
			return -1;
        else if(first.a == 1 && first.b == 1){
            if(second.a !=1 || second.b!=1){
                return -1;
            }
        }
		else if(first.a == second.a && first.b ==second.b && first.time < second.time)
			return -1;
		else if(first.a == 1 && first.b ==0 && second.a == 0 && second.b == 0)
			return -1;
		else if(first.a == 0 && first.b ==1 && second.a == 0 && second.b == 0)
			return -1;
		
		
		return 1;
	}
	
//	public int compare(Book first,Book second) {
//		if(first.time < second.time)
//			return 1;
//		return -1;
//	}
}


