Algorithm/백준

[백준][14888번] 연산자 끼워넣기

1일1코딩 2020. 4. 23. 22:55

https://www.acmicpc.net/problem/14888

 

14888번: 연산자 끼워넣기

첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 곱셈(×)의 개수, 나눗셈(÷)의 개수이다. 

www.acmicpc.net

풀이과정

1. 완전탐색을 이용했다.

 

2. 연산자는 해당 구간에선 1번씩만 이용해보면 된다.

 

소스코드

더보기
#include <stdio.h>
int N;
int map[11] = { 0, };
int oper[4] = { 0, };
int answerMax = -1000000000;
int answerMin = 1000000000;

int calc(int n1, int n2, int op) {
	switch (op)
	{
	case 0: return n1 + n2;
	case 1: return n1 - n2;
	case 2: return n1 * n2;
	case 3: return n1 / n2;
	}
}

void solution(int depth, int sum)
{
	if (depth == N) {
		if (sum > answerMax) {
			answerMax = sum;
		}
		if (sum < answerMin) {
			answerMin = sum;
		}
		return;
	}

	for (int i = 0; i < 4; i++) {
		if (oper[i] > 0) {
			oper[i]--;
			int next = calc(sum, map[depth], i);
			solution(depth + 1, next);
			oper[i]++;
		}
	}
}
int main()
{
	scanf("%d", &N);
	for (int i = 0; i < N; i++) {
		scanf("%d", &map[i]);
	}
	for (int i = 0; i < 4; i++) {
		scanf("%d", &oper[i]);
	}

	solution(1, map[0]);
	printf("%d\n%d\n", answerMax, answerMin);
}

결과