import java.io.*;
import java.util.*;

public class E2 {

	static long m = (long) (1e9 + 7);

	public static void main(String[] args) throws IOException {
		Scanner scn = new Scanner(System.in);
		int n = scn.nextInt();
		int m = scn.nextInt();
		int k = scn.nextInt();
		PriorityQueue<pair> a = new PriorityQueue<>(), b = new PriorityQueue<>();
		PriorityQueue<pair> ab = new PriorityQueue<>();
		PriorityQueue<pair> p123 = 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 {
				p123.add(new pair(t, i + 1, false));
			}
		}
		int tot = 0, c = 0;
		boolean bool = false;
		ArrayList<Integer> al = new ArrayList<>();
		while (k > 0) {
			if (m - c >= 2 && !a.isEmpty() && !b.isEmpty() && !ab.isEmpty()
					&& (a.peek().vv + b.peek().vv) <= ab.peek().vv) {
				pair ff = a.poll();
				pair ss = b.poll();
				tot += ff.vv;
				tot += ss.vv;
				al.add(ff.ii);
				al.add(ss.ii);
				c += 2;
			} else if (!a.isEmpty() && !b.isEmpty() && !ab.isEmpty() && (a.peek().vv + b.peek().vv) > ab.peek().vv) {
				pair ff = ab.poll();

				tot += ff.vv;
				al.add(ff.ii);
				c++;
			} else if (m - c >= 1 && !ab.isEmpty()) {
				pair ff = ab.poll();

				tot += ff.vv;
				al.add(ff.ii);
				c++;
			} else if (m - c >= 2 && !a.isEmpty() && !b.isEmpty()) {
				pair ff = a.poll();
				pair ss = b.poll();
				tot += ff.vv;
				tot += ss.vv;
				al.add(ff.ii);
				al.add(ss.ii);
				c += 2;

			} else {
				bool = true;
				break;
			}
			k--;
		}
		int rr = m - (c);
		while (!ab.isEmpty()) {
			p123.add(ab.poll());
		}
		while (!a.isEmpty()) {
			p123.add(a.poll());

		}
		while (!b.isEmpty()) {
			p123.add(b.poll());
		}
		while (rr > 0) {
			pair pp = p123.poll();
			tot += pp.vv;
			al.add(pp.ii);
			rr--;
		}
		if (bool) {
			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();
		}
	}

	static class pair implements Comparable<pair> {
		int vv;
		int ii;
		boolean b;

		pair(int v, int i, boolean b) {
			this.vv = v;
			this.ii = i;
			this.b = b;
		}

		public int compareTo(pair o) {
			return this.vv - o.vv;
		}
	}

	static class Scanner {

		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s) {
			br = new BufferedReader(new InputStreamReader(s));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}
	}
}