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

public class Main {
	static class Book implements Comparable<Book> {
		int alice;
		int bob;
		int time;

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

		@Override
		public int compareTo(Book o) {

			return Integer.valueOf(this.time).compareTo(o.time);
		}

		@Override
		public String toString() {
			return "Book [alice=" + alice + ", bob=" + bob + ", time=" + time + "]";
		}

	}

	public static int readBooks(List<Book> list, int books) {
		ArrayList<Book> both = new ArrayList<Book>();
		ArrayList<Book> al = new ArrayList<Book>();
		ArrayList<Book> bob = new ArrayList<Book>();
		int a = 0;
		int b = 0;
		for (Book t : list) {
			if (t.alice + t.bob == 2) {
				both.add(t);
				++a;
				++b;
			} else if (t.alice == 1) {
				al.add(t);
				++a;
			} else if (t.bob == 1) {
				bob.add(t);
				++b;
			}
		}
		if (a < books || b < books) {
			return -1;
		}
		Collections.sort(both);
		Collections.sort(al);
		Collections.sort(bob);
		int result = 0;
		int i = 0;
		while (i < both.size() && books != 0) {
			result += both.get(i).time;
			--books;
			++i;
		}
		if (books == 0) {
			return result;
		}
		int t = books;
		i = 0;
		while (i < al.size() && t != 0) {
			result += al.get(i).time;
			++i;
			--t;
		}
		t = books;
		i = 0;
		while (i < bob.size() && t != 0) {
			result += bob.get(i).time;
			++i;
			--t;
		}

		return result;
	}

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line[] = null;
		ArrayList<Book> list = new ArrayList<Book>();
		list.clear();
		line = br.readLine().split(" ");
		int n = Integer.parseInt(line[0]);
		int k = Integer.parseInt(line[1]);
		for (int i = 0; i < n; i++) {
			line = br.readLine().split(" ");
			list.add(new Book(Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[0])));
		}
		System.out.println(readBooks(list, k));

	}

}
