import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {
	static int N, K;
	static PriorityQueue<Point> pq = new PriorityQueue<>();

	static class Point implements Comparable<Point> {
		public int time, alice, bob;

		public Point(int time, int alice, int bob) {
			this.time = time;
			this.alice = alice;
			this.bob = bob;
		}

		@Override
		public int compareTo(Point o) {
			if (this.time < o.time) {
				return -1;
			} else if (this.time > o.time) {
				return 1;
			} else {
				if (this.alice > o.alice) {
					return -1;
				} else if (this.alice < o.alice) {
					return 1;
				} else {
					if (this.bob > o.bob) {
						return -1;
					} else if (this.bob < o.bob) {
						return 1;
					}
				}
			}
			return 0;
		}

	}

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st = new StringTokenizer(br.readLine());
		N = Integer.parseInt(st.nextToken());
		K = Integer.parseInt(st.nextToken());
		pq.clear();
		for (int i = 1; i <= N; i++) {
			st = new StringTokenizer(br.readLine());
			int time = Integer.parseInt(st.nextToken());
			int alice = Integer.parseInt(st.nextToken());
			int bob = Integer.parseInt(st.nextToken());
			pq.offer(new Point(time, alice, bob));
		}

		int aCnt, bCnt, aSum, bSum, sameCnt, sameSum, answer;
		aCnt = bCnt = aSum = bSum = sameCnt = sameSum = answer = 0;
		while (!pq.isEmpty()) {
			Point p = pq.poll();
			if (p.alice == 1) {
				aCnt += 1;
				aSum += p.time;
			}

			if (p.bob == 1) {
				bCnt += 1;
				bSum += p.time;
			}

			if (p.alice == 1 && p.bob == 1) {
				sameCnt += 1;
				sameSum += p.time;
			}

			if (sameCnt == K) {
				answer = sameSum;
				break;
			}

		}

		if (answer == 0) {
			if (aCnt >= K && bCnt >= K) {
				System.out.println(aSum + bSum - sameSum);
			} else {
				System.out.println(-1);
			}
		} else {
			System.out.println(answer);
		}

		bw.close();
	}

}

//5 2
//6 0 0
//9 0 0
//1 0 1
//2 1 1
//5 1 0
