[BOJ] 14888번 연산자 끼워넣기
2024. 8. 24. 17:31ㆍAlgorithm
1. problem :
https://www.acmicpc.net/problem/14888
2. solution 1 :
#include <bits/stdc++.h>
using namespace std;
int n;
int nums[102];
int cal[4]; // + - x / ;
int mxans = -0x7f7f7f7f, mnans = 0x7f7f7f7f;
int temp_sum;
void backTrack(int k) {
if (k == n) {
mxans = max(mxans, temp_sum);
mnans = min(mnans, temp_sum);
return;
}
if (k == 1) temp_sum = nums[0];
for (int i = 0; i < 4; i++) {
if (cal[i] > 0) {
int dormamu = temp_sum;
if (i == 0) {
temp_sum += nums[k];
}
else if (i == 1) {
temp_sum -= nums[k];
}
else if (i == 2) {
temp_sum *= nums[k];
}
else {
if (temp_sum < 0) {
temp_sum = -(-temp_sum / nums[k]);
}
else temp_sum /= nums[k];
}
cal[i] -= 1;
backTrack(k + 1);
temp_sum = dormamu;
cal[i] += 1;
}
}
}
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) cin >> nums[i];
for (int i = 0; i < 4; i++) cin >> cal[i];
backTrack(1);
cout << mxans << '\n';
cout << mnans << '\n';
}
3. solution 2 :
// Authored by : SciEm
// Co-authored by : -
// http://boj.kr/d1e716682fbe499881cd32ec1c235f7e
#include <bits/stdc++.h>
using namespace std;
int nums[12];
int ops[12]; // ops[0]은 항상 더하기
int n;
int mn = 0x7f7f7f7f, mx = -0x7f7f7f7f;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++)
cin >> nums[i];
for (int op = 0, idx = 1; op < 4; op++) {
int x; cin >> x;
while (x--)
ops[idx++] = op;
}
do {
int res = 0;
for (int i = 0; i < n; i++) {
if (ops[i] == 0) res += nums[i];
else if (ops[i] == 1) res -= nums[i];
else if (ops[i] == 2) res *= nums[i];
else res /= nums[i];
}
mx = max(mx, res);
mn = min(mn, res);
} while (next_permutation(ops + 1, ops + n));
cout << mx << '\n' << mn;
}
source code 출처 : https://github.com/encrypted-def/basic-algo-lecture/blob/master/0x0D/solutions/14888_1.cpp
basic-algo-lecture/0x0D/solutions/14888_1.cpp at master · encrypted-def/basic-algo-lecture
바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.
github.com
'Algorithm' 카테고리의 다른 글
[BOJ] 15685번 : 드래곤 커브 (0) | 2024.08.25 |
---|---|
[BOJ] 14889번 : 스타트와 링크 (0) | 2024.08.24 |
[BOJ] 14502번 : 연구소 (0) | 2024.08.24 |
[BOJ] 13460번 : 구슬 탈출 2 (0) | 2024.08.24 |
[BOJ] 14500번 : 테트로미노 (0) | 2024.08.23 |