

import java.util.*;

public class pract{
	 public static int mysol(int n){
		  int arr[]=new int[n];
		  int rr=0;
		  for(int i=0;i<n;i++){
			  arr[i]=i;
			  rr+=i;
		  }
		  return rr;
	  }
		static class pair implements Comparable<pair>{
			int val;
			int ind;
			boolean b;
			pair(int v,int i,boolean bb){
				val=v;
				ind=i;
				b=bb;
			}
			@Override
			public int compareTo(pair o) {
				// TODO Auto-generated method stub
				return this.val-o.val;
			}
		}
		
		public static void main(String[] args)  {
			Scanner scn = new Scanner(System.in);
			
				int n=scn.nextInt();
				int m=scn.nextInt();
				int k=scn.nextInt();
				PriorityQueue<pair> a=new PriorityQueue<>();
				PriorityQueue<pair> b=new PriorityQueue<>();
				PriorityQueue<pair> ab=new PriorityQueue<>();
				PriorityQueue<pair> faltu=new PriorityQueue<>();

				for(int i=0;i<n;i++){
					int t=scn.nextInt();
					int f=scn.nextInt();
					int s=scn.nextInt();
					if(f==1 && s==1){
						ab.add(new pair(t,i+1,true));
					}else if(f==1){
						a.add(new pair(t,i+1,false));
					}else if(s==1){
						b.add(new pair(t,i+1,false));
					}else{
						faltu.add(new pair(t,i+1,false));
					}
				}
				int tot=0;
				int k1=k,k2=k,c=0;
				boolean f=false;
				ArrayList<Integer> al=new ArrayList<>();
				while(k>0){
					if(!a.isEmpty() && !b.isEmpty() && !ab.isEmpty() && (a.peek().val+b.peek().val)>=ab.peek().val){
						pair ff=ab.poll();
						
						tot+=ff.val;
						al.add(ff.ind);
						c++;
					}
					
					else if(m-c>=2 && !a.isEmpty() && !b.isEmpty() && !ab.isEmpty() && (a.peek().val+b.peek().val)<ab.peek().val){
						pair ff=a.poll();
						pair ss=b.poll();
						tot+=ff.val;
						tot+=ss.val;
						al.add(ff.ind);
						al.add(ss.ind);
						c+=2;
					}
					else if(m-c>=1 && !ab.isEmpty()){
						pair ff=ab.poll();
						
						tot+=ff.val;
						al.add(ff.ind);
						c++;
					}else if(m-c>=2 && !a.isEmpty() && !b.isEmpty()){
						pair ff=a.poll();
						pair ss=b.poll();
						tot+=ff.val;
						tot+=ss.val;
						al.add(ff.ind);
						al.add(ss.ind);
						c+=2;
						
					}else{
						f=true;
						break;
					}
					k--;
				}
				int rr=m-(c);
				while(!ab.isEmpty()){
					faltu.add(ab.poll());
				}
				while(!a.isEmpty()){
					faltu.add(a.poll());
					
				}
				while(!b.isEmpty()){
					
					faltu.add(b.poll());
				}
				while(rr>0){
					pair pp=faltu.poll();
					tot+=pp.val;
					al.add(pp.ind);
					rr--;
				}
				if(f){
					System.out.println(-1);
					
				}else{
					System.out.println(tot);
					for(int i=0;i<al.size();i++){
						System.out.print(al.get(i)+" ");
					}
					System.out.println();
				}
			

			}
	}