        import java.util.*; 
        import java.lang.*; 
        import java.io.*;
     
        public class S{
            public static void main(String[] args) {
		        Integer[][] books = null;

        		 Scanner sc = new Scanner(System.in);
    			String firstLine = sc.nextLine();
    			
    			String[] lineArray = firstLine.split(" ");
    			int rowCount = Integer.valueOf(lineArray[0]);
    			int minLikeCount = Integer.valueOf(lineArray[1]);
    			
    			books = new Integer[rowCount][3]; 
    			
    			for(int i=0; i<rowCount; i++) {
    				String line = sc.nextLine();
    				String[] items = line.split(" ");
    				for(int j=0; j<3; j++) {
    					books[i][j]=Integer.valueOf(items[j]);
    				}
    			}
    			
    			Arrays.sort(books, new java.util.Comparator<Integer[]>() {
    			    public int compare(Integer[] a, Integer[] b) {
    			        return Integer.compare(a[0], b[0]);
    			    }
    			});
    			System.out.println(readingBooksEasyVersion(books, minLikeCount));
        	}
            	
            private static int readingBooksEasyVersion(Integer[][] array, int likeCount) {
        		int readingTimeTogether=0;
        		int readingTime =0;
        		int girlLikeCounter=0;
        		int boyLikeCounter=0;
        		boolean canReadTogether = false;
        		for(int i=0; i<array.length; i++) {
        
        			if(array[i][1]==1 && array[i][2]==1) {
        				readingTimeTogether+=array[i][0];
        				girlLikeCounter++;
        				boyLikeCounter++;
        			}
        			
        			if(boyLikeCounter==likeCount && girlLikeCounter==likeCount) {
        				System.out.println("Set boolean flag TRUE");
        				canReadTogether=true;
        				break;
        			}
        		}
        		
        		girlLikeCounter=0;
        		boyLikeCounter=0;
        		
        		for(int i=0; i<array.length; i++) {
        			if(array[i][1]==1 && array[i][2]==1) {
        				readingTime+=array[i][0];
        				girlLikeCounter++;
        				boyLikeCounter++;
        			}else if(array[i][1]==1) {
        				readingTime+=array[i][0];
        				girlLikeCounter++;
        			}else if(array[i][2]==1) {
        				readingTime+=array[i][0];
        				boyLikeCounter++;
        			}
        		}
        
        		if(canReadTogether) {
        			return readingTimeTogether<readingTime ? readingTimeTogether : readingTime;
        		}
        		
        		if(boyLikeCounter!=likeCount && girlLikeCounter!=likeCount) {
        			return -1;
        		}
        		return readingTime;
        	}
        }