import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;



public class main {
	
	public static void main(String[] args) throws NumberFormatException, IOException
	{
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		PrintWriter pw= new PrintWriter(System.out);
		StringTokenizer st= new StringTokenizer(br.readLine());
		int n= Integer.parseInt(st.nextToken());
		int k= Integer.parseInt(st.nextToken());
		ArrayList<book> Both=new ArrayList();
		ArrayList<book> Alice=new ArrayList();
		ArrayList<book> Bob=new ArrayList();
		for (int i = 0; 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());
			if(alice==1 && bob==1)
			{
				Both.add(new book(time, alice, bob));
			}
			else if(alice==1) {
				Alice.add(new book(time, alice, bob));
			}
			else if(bob==1)
			{
				Bob.add(new book(time, alice, bob));
			}	
		}
		Collections.sort(Both);
		Collections.sort(Alice);
		Collections.sort(Bob);
		int bobFirst=0;
		int aliceFirst=0;
		int bothFirst=0;
		//System.out.println(Both);
		//System.out.println(Alice);
		//System.out.println(Bob);
		int a=k;
		int b=k;
		int totalTime=0;
		
		while(b>0)
		{
			if(bothFirst==Both.size() && bobFirst==Bob.size())
			{
				totalTime=-1;break;
			}
			if(bobFirst==Bob.size() || (!(bothFirst==Both.size()) && Both.get(bothFirst).time<=Bob.get(bobFirst).time))
			{			
				totalTime+=Both.get(bothFirst++).time;
				a--; b--;
			}
			else if(bothFirst==Both.size() || Both.get(bothFirst).time>Bob.get(bobFirst).time)
			{
				totalTime+=Bob.get(bobFirst++).time;
				b--;
			}
		}
		
		while(a>0)
		{
			if(bothFirst==Both.size() && aliceFirst==Alice.size())
			{
				totalTime=-1;break;
			}
			else if(aliceFirst==Alice.size() || (!(bothFirst==Both.size()) && Both.get(bothFirst).time<=Alice.get(aliceFirst).time))
			{
				totalTime+=Both.get(bothFirst++).time;
				a--; b--;
			}
			else if(bothFirst==Both.size() || Both.get(bothFirst).time>Alice.get(aliceFirst).time)
			{
				totalTime+=Alice.get(aliceFirst++).time;
				a--;
			}
		}
		
		pw.println(totalTime);
		pw.close();
	}
	
	static class book implements Comparable<book>
	{
		int time;
		int alice;
		int bob;
		public book(int time, int alice, int bob) {
			this.time=time;
			this.alice=alice;
			this.bob=bob;
		}
		@Override
		public int compareTo(book b){
			return this.time-b.time;
		}
		public String toString()
		{
			return time+"";
		}
	}
}
