본문 바로가기
알고리즘/백준

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

by 컴공맨 2020. 5. 30.
 

14888번: 연산자 끼워넣기

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

www.acmicpc.net


문제

백준문제이미지


풀이

연산자의 수는 입력받은 수보다 1개가 적다.

 

각각의 연산자에 숫자를 부여하고 부여한 숫자를 연산자의 수 만큼 배열에 차례대로 추가하여 순열을 사용하면 된다.


문제점

첫째 줄에 최댓값을, 둘째 줄에는 최솟값을 출력해야 하는데 반대로 출력해버린 실수를 저질렀다...

minmax_element를 사용할 때 second에 최댓값, first에 최솟값임을 주의하자!


코드

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

int calc(vector<int> &a, vector<int> &b)
{
    int n = a.size();
    int ans = a[0];

    for (int i = 1; i < n; ++i)
    {
        if (b[i - 1] == 0)
        {
            ans = ans + a[i];
        }
        else if (b[i - 1] == 1)
        {
            ans = ans - a[i];
        }
        else if (b[i - 1] == 2)
        {
            ans = ans * a[i];
        }
        else if (b[i - 1] == 3)
        {
            ans = ans / a[i];
        }
    }

    return ans;
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);

    int n;
    cin >> n;

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

    vector<int> b;
    for (int i = 0; i < 4; ++i)
    {
        int cnt;
        cin >> cnt;
        for (int k = 0; k < cnt; ++k)
        {
            b.push_back(i);
        }
    }
    sort(b.begin(), b.end());
    
    vector<int> result;
    
    do
    {
        int temp = calc(a, b);
        result.push_back(temp);
    } while (next_permutation(b.begin(), b.end()));

    auto ans = minmax_element(result.begin(), result.end());
    cout << *ans.second << "\n";
    cout << *ans.first << "\n";

    return 0;
    
}

결과

결과 이미지


 

 

pyo7410/Study

Contribute to pyo7410/Study development by creating an account on GitHub.

github.com