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

public class test1 {

	static class Reader {
		BufferedReader br;
		StringTokenizer st;

		public Reader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		public int nextInt() throws IOException {
			if (st == null || !st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine());
			}
			return Integer.parseInt(st.nextToken());
		}

		public float nextFloat() throws IOException {
			if (st == null || !st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine());
			}
			return Float.parseFloat(st.nextToken());
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public String next() throws IOException {
			if (st == null || !st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine());
			}
			return st.nextToken();
		}
	}

	static class Book implements Comparable<Book>{
		int time;
		boolean a,b;
		public Book(int time, boolean a, boolean b) {
			this.time = time;
			this.a = a;
			this.b = b;
		}
		@Override
		public int compareTo(Book o) {
			int ta = (this.a?1:0)+(this.b?1:0);
			int tb = (o.a?1:0)+(o.b?1:0);
			if(ta==tb) {
				return this.time-o.time;
			}
			return tb-ta;
		}
		
	}
	public static void main(String[] args) throws Exception {
		Reader sc = new Reader();
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		try {
			int n = sc.nextInt();
			int k = sc.nextInt();
			Book[] arr = new Book[n];
			int c1 = 0, c2 = 0;
			for(int i=0;i<n;i++) {
				int time = sc.nextInt();
				int t1 = sc.nextInt();
				int t2 = sc.nextInt();
				c1+=t1;
				c2+=t2;
				boolean a = t1==1?true:false;
				boolean b = t2==1?true:false;
				arr[i] = new Book(time,a,b);
			}
			if(c1<k || c2<k) {
				out.println(-1);
			} else {
				Arrays.sort(arr);
//				for(int i=0;i<n;i++) {
//					System.out.println(arr[i].time+" "+arr[i].a+" "+arr[i].b);
//				}
				long min = Long.MAX_VALUE;
				int a = 0, b = 0;
				int last = -1;
				long curr = 0;
				for(int i=0;i<n;i++) {
					Book temp = arr[i];
					curr+=temp.time;
					if(temp.a)
						a++;
					if(temp.b)
						b++;
					while(a>=k && b>=k) {
						min = Math.min(curr, min);
						last++;
						curr-=arr[last].time;
						if(arr[last].a)
							a--;
						if(arr[last].b)
							b--;
					}
					if(!temp.a && !temp.b)
						break;
				}
				out.println(min);
			}
			out.flush();
		} catch (Exception e) {

		}
	}
}
