//package round_653_div3;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class E1 {
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		String[] ip = br.readLine().split(" ");
		
		int n = Integer.parseInt(ip[0]);
		int k = Integer.parseInt(ip[1]);
		
		List<Info> list = new ArrayList<>();
		List<Info> abList = new ArrayList<>();
		
		long ans = 0;
		
		for(int i = 0 ; i < n ; i++) {
			ip = br.readLine().split(" ");
			int t = Integer.parseInt(ip[0]);
			int a = Integer.parseInt(ip[1]);
			int b = Integer.parseInt(ip[2]);
			
			if(a == 0 && b == 0) continue;
			
			if(a == 1 && b == 1 ) {
				list.add(new Info(t,a,b));
			}else if(a == 0 && b == 1){
				abList.add(new Info(t,a,b));
			}else {
				abList.add(new Info(t,a,b));
			}
		}
		
		//ans=  -1;
		
		List<Info> finalList = new ArrayList<>();
		
		finalList.addAll(list);
		
		int a_read = finalList.size();
		int b_read = a_read;
		
		if(k-finalList.size() > 0) {
			Collections.sort(abList, (a,b) -> a.t- b.t);

			int idx = 0;
			while(a_read < k || b_read < k) {
				if(idx == abList.size()) break;
				Info temp = abList.get(idx++);
				finalList.add(temp);
				if(temp.a == 1) a_read++;
				if(temp.b == 1) b_read++;
			}
		}
		
		if(a_read < k || b_read < k) {
			ans = -1;
		}else{
			for(Info a : finalList) {
				ans += a.t;
			}
		}
		
		
		System.out.println(ans);
	}
}

class Info{
	int t;
	int a;
	int b;
	
	public Info(int t, int a, int b) {
		this.t = t;
		this.a = a;
		this.b = b;
	}
	
	public int hashCode() {
		return (t+"_"+a+"_"+b).hashCode();
	}
	
	public boolean equals(Object obj) {
		if(obj instanceof Info) {
			Info objI = (Info)obj;
			return this.t == objI.t && this.a == objI.a && this.b == objI.b;
		}
		
		return false;
	}
}
