|
| 1 | +package bruteForce.n15659; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 8 | + static StringTokenizer st; |
| 9 | + static int N, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; |
| 10 | + static int[] num, select, operator = new int[4]; // +, -, *, / |
| 11 | + |
| 12 | + public static void main(String[] args) throws Exception { |
| 13 | + init(); |
| 14 | + dfs(0); |
| 15 | + System.out.println(max); |
| 16 | + System.out.println(min); |
| 17 | + } |
| 18 | + |
| 19 | + private static void dfs(int idx) { |
| 20 | + if (idx == N - 1) { |
| 21 | + calculate(); |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + for (int i = 0; i < 4; i++) { |
| 26 | + if (operator[i] == 0) continue; |
| 27 | + |
| 28 | + select[idx] = i; |
| 29 | + operator[i]--; |
| 30 | + dfs(idx + 1); |
| 31 | + operator[i]++; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + private static void calculate() { |
| 36 | + Deque<Integer> oq = new LinkedList<>(); |
| 37 | + Deque<Integer> nq = new LinkedList<>(); |
| 38 | + nq.offer(num[0]); |
| 39 | + |
| 40 | + for (int i = 0; i < N - 1; i++) { |
| 41 | + if (select[i] <= 1) { |
| 42 | + oq.offerLast(select[i]); |
| 43 | + nq.offerLast(num[i + 1]); |
| 44 | + } else if (select[i] == 2) { |
| 45 | + nq.offerLast(nq.pollLast() * num[i + 1]); |
| 46 | + } else { |
| 47 | + nq.offerLast(nq.pollLast() / num[i + 1]); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + int res = nq.poll(); |
| 52 | + |
| 53 | + while (!oq.isEmpty()) { |
| 54 | + int o = oq.poll(); |
| 55 | + int n = nq.poll(); |
| 56 | + |
| 57 | + if (o == 0) res += n; |
| 58 | + else res -= n; |
| 59 | + } |
| 60 | + |
| 61 | + max = Math.max(res, max); |
| 62 | + min = Math.min(res, min); |
| 63 | + } |
| 64 | + |
| 65 | + private static void init() throws Exception { |
| 66 | + N = Integer.parseInt(br.readLine()); |
| 67 | + num = new int[N]; |
| 68 | + select = new int[N - 1]; |
| 69 | + |
| 70 | + st = new StringTokenizer(br.readLine()); |
| 71 | + for (int i = 0; i < N; i++) num[i] = Integer.parseInt(st.nextToken()); |
| 72 | + |
| 73 | + st = new StringTokenizer(br.readLine()); |
| 74 | + for (int i = 0; i < 4; i++) operator[i] = Integer.parseInt(st.nextToken()); |
| 75 | + } |
| 76 | +} |
0 commit comments