import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

public class ProblemE1 {

	public static void main(String[] args) {
		MyScanner in = new MyScanner();

		int n = in.nextInt();
		int k = in.nextInt();

		List<Book> both = new ArrayList<>();
		List<Book> alice = new ArrayList<>();
		List<Book> bob = new ArrayList<>();

		for (int i = 0; i < n; i++) {
			int t = in.nextInt();
			int a = in.nextInt();
			int b = in.nextInt();
			
			Book book = new Book();
			book.time = t;
			book.a = a;
			book.b = b;
			
			if (a == 1 && b == 1) {
				both.add(book);
			} else if (a == 1) {
				alice.add(book);
			} else if (b == 1) {
				bob.add(book);
			}

		}

		if (both.size() + alice.size() < k || both.size() + bob.size() < k) {
			System.out.println(-1);
		} else {
			Collections.sort(both);
			Collections.sort(alice);
			Collections.sort(bob);
			
			Collections.reverse(both);
			
			List<Book> combined = new ArrayList();
			for(int i = 0; i < alice.size() && i < bob.size(); i++) {
				Book book = new Book();
				book.time = alice.get(i).time + bob.get(i).time;
				
				combined.add(book);
			}
			both.addAll(combined);
			
			int min = 0;
			for(int i = 0; i < k; i++) {
				min += both.get(i).time;
			}
			
			for (int i = k; i < both.size(); i++) {
				int time = min - both.get(i - k).time + both.get(k).time;
				if (time > 0) {
					min = Math.min(time, min);
				}
			}
			
			System.out.println(min);
		}

	}

	private static class Book implements Comparable<Book> {
		int time;
		int a;
		int b;

		@Override
		public int compareTo(Book o) {
			if (time < o.time)
				return -1;
			if (time > o.time)
				return 1;
			return 0;
		}
	}

	// -----------MyScanner class for faster input----------
	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
	}
}
