|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N; |
| 7 | + static int mp, mf, ms, mv; |
| 8 | + static int[][] foods; |
| 9 | + static int minCost = Integer.MAX_VALUE; |
| 10 | + static List<Integer> result = new ArrayList<>(); |
| 11 | + |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + N = Integer.parseInt(br.readLine()); |
| 15 | + |
| 16 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 17 | + mp = Integer.parseInt(st.nextToken()); |
| 18 | + mf = Integer.parseInt(st.nextToken()); |
| 19 | + ms = Integer.parseInt(st.nextToken()); |
| 20 | + mv = Integer.parseInt(st.nextToken()); |
| 21 | + |
| 22 | + foods = new int[N][5]; |
| 23 | + for (int i = 0; i < N; i++) { |
| 24 | + st = new StringTokenizer(br.readLine()); |
| 25 | + for (int j = 0; j < 5; j++) { |
| 26 | + foods[i][j] = Integer.parseInt(st.nextToken()); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + backtrack(0, 0, 0, 0, 0, 0, new ArrayList<>()); |
| 31 | + |
| 32 | + if (minCost == Integer.MAX_VALUE) { |
| 33 | + System.out.println(-1); |
| 34 | + } else { |
| 35 | + System.out.println(minCost); |
| 36 | + for (int i = 0; i < result.size(); i++) { |
| 37 | + if (i > 0) System.out.print(" "); |
| 38 | + System.out.print(result.get(i)); |
| 39 | + } |
| 40 | + System.out.println(); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + static void backtrack(int idx, int protein, int fat, int carbo, int vitamin, |
| 45 | + int cost, List<Integer> selected) { |
| 46 | + if (protein >= mp && fat >= mf && carbo >= ms && vitamin >= mv) { |
| 47 | + if (cost < minCost) { |
| 48 | + minCost = cost; |
| 49 | + result = new ArrayList<>(selected); |
| 50 | + } |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + if (idx == N || cost >= minCost) return; |
| 55 | + |
| 56 | + selected.add(idx + 1); |
| 57 | + backtrack(idx + 1, protein + foods[idx][0], fat + foods[idx][1], |
| 58 | + carbo + foods[idx][2], vitamin + foods[idx][3], |
| 59 | + cost + foods[idx][4], selected); |
| 60 | + selected.remove(selected.size() - 1); |
| 61 | + |
| 62 | + backtrack(idx + 1, protein, fat, carbo, vitamin, cost, selected); |
| 63 | + } |
| 64 | +} |
| 65 | +``` |
0 commit comments