import java.util.Scanner;

public class ReadingBook
{
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int k=sc.nextInt();
		int books=0,books1=0,alice=0,bob=0,alice1=0,bob1=0,alice2=0,bob2=0,books2=0;
		while(n-- >0)
		{
			int t=sc.nextInt();
			int a=sc.nextInt();
			int b=sc.nextInt();
			if(k==1)
			{
				if(t==1 && a==1 && b==1)
				{
					System.out.println(t);
					break;
				}
			}
			else
			{
				if(a==1 && b==1)
				{
					books+=t;
					bob++;
					alice++;
				}
				if(a==1 && b==0)			
				{
					books1+=t;
					alice1++;
				}
				if(a==0 && b==1)			
				{
					books1+=t;
					bob1++;
				}
				if(a==1 && b==0)
				{
					books2+=t;
					alice2++;
				}
				if(a==0 && b==1)
				{
					books2+=t;
					bob2++;
				}
				if(a==1 && b==1)
				{
					books2+=t;
					bob2++;
					alice2++;
				}
				
			}
		}
		if(k>1)
		{
			if(bob==k && alice==k)
				System.out.println(books);
			else if(bob1==k && alice1==k)
				System.out.println(books1);
			else if(bob2==k && alice2==k)
				System.out.println(books2);
			else
				System.out.println(-1);
		}
		
	}
}
