728x90
https://www.acmicpc.net/problem/15658
15658번: 연산자 끼워넣기 (2)
첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1보다 크거나 같고, 4N보다 작거나 같은 4개의 정수가 주어지는데, 차례대
www.acmicpc.net
숫자는 고정이고 연산자만 골라서(Backtracking) 연산해주고 결괏값을 Min, Max 구해주면 된다.
여기서 주의할 것은 최대 10억 최소 -10억이라는 것이다. 이걸 까먹고 안해서 틀렸다..^^ㅋㅋㅋㅋ
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int n, arr[12], minv=1000000001, maxv=-1000000001;
int op[4]; //+, -, *, /
vector<int> v;
int calc(){
int result = arr[0];
for(int i=0; i<v.size(); i++){
if(v[i] == 0){ // +
result += arr[i+1];
}else if(v[i] == 1){ // -
result -= arr[i+1];
}else if(v[i] == 2){ // *
result *= arr[i+1];
}else if(v[i] == 3){ // /
result /= arr[i+1];
}
}
return result;
}
void BT(int cnt){
if(cnt == n-1){
int result = calc();
minv = min(minv, result);
maxv = max(maxv, result);
return;
}
for(int i=0; i<4; i++){ //연산자
if(op[i] != 0){
op[i]--;
v.push_back(i); //연산자 번호 넣기 (+:0, -:1, *:2, /:3)
BT(cnt+1);
v.pop_back();
op[i]++;
}
}
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
for(int i=0; i<n; i++) cin >> arr[i];
for(int i=0; i<4; i++) cin >> op[i];
BT(0);
cout << maxv << '\n' << minv << '\n';
return 0;
}
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[백준/c++] 16198번: 에너지 모으기 (0) | 2022.07.29 |
---|---|
[백준/c++] 14225번: 부분수열의 합 (0) | 2022.07.29 |
[백준/c++] 1476번: 날짜 계산 (0) | 2022.07.29 |
[백준/c++] 1285번: 동전 뒤집기 (0) | 2022.07.29 |
[백준/c++] 13458번: 시험 감독 (0) | 2022.07.27 |