티스토리 뷰

 

간단한 완전탐색 문제다

경우의수가 적기 때문에 연산자가 있는대로 다 넣어보면 된다

 

op배열에 연산자를 넣고 해당연산자가 남아있으면 

수를 줄이고 넣어서 다음 숫자로 넘어가고

다시 수를 처음처럼 늘려준다

 

재귀를 타고 들어가기 때문에 연산한 결과를 계속 가져갔다가

원래대로 돌려준다

 

소스코드

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
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int n;
int op[4]; //+,-,x,/;
int a[22],b[22];
int maxn = -1000000005;
int minn = -maxn;
 
void solve(int pos){
    if(pos==n-1){
        maxn = max(maxn,b[pos]);
        minn = min(minn,b[pos]);
        return;
    }
 
    for(int i=0;i<4;i++){
        if(op[i]){
            op[i]--;
            if(i==0) b[pos+1]=b[pos]+a[pos+1];
            else if(i==1) b[pos+1]=b[pos]-a[pos+1];
            else if(i==2) b[pos+1]=b[pos]*a[pos+1];
            else b[pos+1]=b[pos]/a[pos+1];
            solve(pos+1);
            op[i]++;
        }
    }
}
 
int main(){
    //freopen("input.txt","r",stdin);
    scanf(" %d",&n);
    for(int i=0;i<n;i++scanf(" %d",&a[i]);
    for(int i=0;i<4;i++scanf(" %d",&op[i]);
    b[0]=a[0];
    solve(0);
    printf("%d\n",maxn);
    printf("%d\n",minn);
}
 
 

'알고리즘 > BOJ' 카테고리의 다른 글

[백준] 15990 1,2,3 더하기 5  (0) 2020.01.24
[백준] 15988 1,2,3 더하기 3  (0) 2020.01.24
[백준] 17505 링고와 순열  (0) 2019.11.08
[백준] 17503 맥주 축제  (0) 2019.11.08
[백준] 17499 수열과 시프트 쿼리  (0) 2019.11.08
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
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
글 보관함