Skip to content

Commit

Permalink
백준 15658 풀이
Browse files Browse the repository at this point in the history
  • Loading branch information
mtjin committed Mar 9, 2022
1 parent d6c5f1a commit d982e5e
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
53 changes: 53 additions & 0 deletions 백준 15658 연산자 끼워넣기 (2) -백트래킹-/Main.java
@@ -0,0 +1,53 @@
import java.util.Scanner;

public class Main {
private static int N;
private static int[] op = new int[4];
private static int[] arr;
private static int max = Integer.MIN_VALUE;
private static int min = Integer.MAX_VALUE;

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < 4; i++) {
op[i] = sc.nextInt();
}
dfs(1, op, arr[0]);
System.out.println(max);
System.out.println(min);
}

private static void dfs(int depth, int[] op, int result) {
if (depth == N) {
max = Math.max(max, result);
min = Math.min(min, result);
return;
}
for (int i = 0; i < 4; i++) {
if (op[i] == 0) {
continue;
}
op[i]--;
switch (i) {
case 0:
dfs(depth + 1, op, result + arr[depth]);
break;
case 1:
dfs(depth + 1, op, result - arr[depth]);
break;
case 2:
dfs(depth + 1, op, result * arr[depth]);
break;
case 3:
dfs(depth + 1, op, result / arr[depth]);
break;
}
op[i]++;
}
}
}
43 changes: 43 additions & 0 deletions 백준 15658 연산자 끼워넣기 (2) -백트래킹-/Main.kt
@@ -0,0 +1,43 @@
import java.util.*


private var N = 0
private val op = IntArray(4)
private lateinit var arr: IntArray
private var max = Int.MIN_VALUE
private var min = Int.MAX_VALUE
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
N = sc.nextInt()
arr = IntArray(N)
for (i in 0 until N) {
arr[i] = sc.nextInt()
}
for (i in 0..3) {
op[i] = sc.nextInt()
}
dfs(1, op, arr[0])
println(max)
println(min)
}

private fun dfs(depth: Int, op: IntArray, result: Int) {
if (depth == N) {
max = Math.max(max, result)
min = Math.min(min, result)
return
}
for (i in 0..3) {
if (op[i] == 0) {
continue
}
op[i]--
when (i) {
0 -> dfs(depth + 1, op, result + arr[depth])
1 -> dfs(depth + 1, op, result - arr[depth])
2 -> dfs(depth + 1, op, result * arr[depth])
3 -> dfs(depth + 1, op, result / arr[depth])
}
op[i]++
}
}

0 comments on commit d982e5e

Please sign in to comment.