PS

14888. 연산자 끼워넣기

tose33 2020. 10. 1. 17:53

www.acmicpc.net/problem/14888

 

14888번: 연산자 끼워넣기

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

www.acmicpc.net

 

비슷하게 next_permutation을 써서

연산자의 순서를 바꿔주면 된다.

 

#include <iostream>
using namespace std;
#include <algorithm>
#include <vector>

int main() {
	int a[20]; // num
	int b[20]; // 연산자
	vector <int> c;

	int n;
	cin >> n;

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

	for (int i = 1; i <= 4; i++) { // b
		cin >> b[i];
	}

	for (int i = 1; i <= 4; i++) { // 연산자 나열
		for (int j = 0; j < b[i]; j++) {
			c.push_back(i);
		}
	}

	int big, small;
	int cnt = 0;
	do { // 순열 계속 바꿈
		int res = a[0];
		for (int j = 0; j < n - 1; j++) {
			if (c[j] == 1) {
				res += a[j + 1];

			}
			else if (c[j] == 2) {
				res -= a[j + 1];

			}
			else if (c[j] == 3) {
				res *= a[j + 1];

			}
			else if (c[j] == 4) {
				res /= a[j + 1];

			}
		}

		if (cnt == 0) { // 최초 1회만
			big = res;
			small = res;
		}
		cnt++;

		big = max(big, res);
		small = min(small, res);


	} while (next_permutation(c.begin(), c.end()));

	cout << big << "\n" << small;


}