Notice
Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

코린이 탈출기

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

문제 풀이/DFS

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

명란파스타 2020. 7. 25. 16:04

문제 바로가기

 

14888번: 연산자 끼워넣기

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

www.acmicpc.net

 

딱 문제를 읽어보면 백트래킹 냄새가 솔솔 ~

 

역시나 백트래킹으로 구현하니 아주 쉽게 풀 수 있었다

백트래킹으로 문제를 풀 때는, 기존의 상태에서 어떠한 연산이나 수행으로 바뀐 상태를 다시 원래대로 돌려놓는 것이 중요하다.

dfs()함수에서 다른 상태로 갈 때 바뀌는 값이 res와 2차원 배열 visited 이므로, 재귀함수를 호출한뒤 다시 원래의 res와 visited로 돌려주어야한다.

 

또한, digit(연산자 개수) == n-1은 재귀함수의 탈출조건이므로, 이때 최대값과 최소값을 갱신시켜준다.

 

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int n;
int _number[11];
int visited[10];

vector<int> _operator; //0:+, 1:-, 2:*, 3: /
long maxx = -1000000000, minn = 1000000000;

int calculate(long n1, long n2, int oper)
{
	long result = 0;
	switch (oper) {
	case 0:
		result = n1 + n2;
		break;
	case 1:
		result = n1 - n2;
		break;
	case 2:
		result = n1*n2;
		break;
	case 3:
		result = n1/n2;
		break;
	}

	return result;
}

void dfs(long res, int digit)
{
	if (digit == n - 1)
	{
		maxx = max(maxx, res);
		minn = min(minn, res);
		return;
	}
		

	for (int i = 0; i < _operator.size(); i++)
	{
		if (!visited[i]) {
			int tmp = res;
			res = calculate(res, _number[digit + 1], _operator[i]);
			visited[i] = 1;
			dfs(res, digit + 1);
			visited[i] = 0;
			res = tmp;
		}	
	}
	

}

int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> _number[i];
	}

	for(int i = 0; i<4; i++)
	{
		int tmp;
		cin >> tmp;
		for (int j = 0; j < tmp; j++)
		{
			_operator.push_back(i);
		}
	}

	dfs(_number[0], 0);

	cout << maxx << endl << minn << endl;
	return 0;

}

'문제 풀이 > DFS' 카테고리의 다른 글

[백준 15683] 감시  (0) 2020.07.27
[백준 14889] 스타트와 링크  (0) 2020.07.25
[백준 14891] 톱니바퀴  (0) 2020.07.22
[백준 19236] 청소년 상어  (0) 2020.07.22