๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 14888๋ฒˆ - ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ

by dkswnkk 2022. 2. 17.

๋ฌธ์ œ

 

14888๋ฒˆ: ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ

์ฒซ์งธ ์ค„์— ์ˆ˜์˜ ๊ฐœ์ˆ˜ N(2 ≤ N ≤ 11)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” A1, A2, ..., AN์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ Ai ≤ 100) ์…‹์งธ ์ค„์—๋Š” ํ•ฉ์ด N-1์ธ 4๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, ์ฐจ๋ก€๋Œ€๋กœ ๋ง์…ˆ(+)์˜ ๊ฐœ์ˆ˜, ๋บ„์…ˆ(-)์˜ ๊ฐœ์ˆ˜, 

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <vector>

using namespace std;

int N,add,sub,mul,divd;
int max_v=-1e9-1, min_v = 1e9+1;

void backtrack(int result,int index, vector<int>&num, int add, int sub, int mul, int divd){
    
    if(index==N){
        max_v = max(max_v, result);
        min_v = min(min_v, result);
        return;
    }
    
    if(add>0) backtrack(result+num[index], index+1, num, add-1, sub, mul, divd);
    if(sub>0) backtrack(result-num[index], index+1, num, add, sub-1, mul, divd);
    if(mul>0) backtrack(result*num[index], index+1, num, add, sub, mul-1, divd);
    if(divd>0) backtrack(result/num[index], index+1, num, add, sub, mul, divd-1);
    
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin>>N;
    vector<int>num(N);
    
    for(int i=0; i<N; i++) cin>>num[i];
    cin>>add>>sub>>mul>>divd;
    backtrack(num[0],1,num,add,sub,mul,divd);
    cout<<max_v<<'\n'<<min_v;
}

 

ํ’€์ด

๋ชจ๋“  ์—ฐ์‚ฐ์˜ ๊ฒฝ์šฐ๋ฅผ ๋Œ์•„๋ณด๋ฉฐ ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’์„ ๊ฐฑ์‹ ํ•˜๋Š” ์™„์ „ ํƒ์ƒ‰์„ ํ†ตํ•ด ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ฒ˜์Œ์— ์„ค๊ณ„๋งŒ ์–ด๋–ป๊ฒŒ ํ• ์ง€ ๋– ์˜ฌ๋ฆฌ๋ฉด ์‰ฌ์šด ๋ฌธ์ œ์˜€๋Š”๋ฐ ์š”์ฆ˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์•ˆ ํ’€๋‹ค ๋ณด๋‹ˆ ๋จธ๋ฆฌ๊ฐ€ ๊ตณ์–ด์„œ next_permuation์„ ํ†ตํ•ด ์ˆœ์—ด๋กœ ๊ตฌํ˜„ํ•ด๋ณด๋ ค๋‹ค๊ฐ€ ์•ˆํ’€๋ ค์„œ ํ”ผ๋ฅผ ๋ณธ ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.๐Ÿ˜ข

๋Œ“๊ธ€