[BOJ] 16638 괄호 추가하기 2

Time Lapse :16min 23sec

16638.cpp

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int len;
bool garo[19];
string str;
pair<bool, int> ans;
string solution(char a, char b, char op){
return op == '+' ? to_string(a-'0'+b-'0') : op == '-' ? to_string(a-b) : to_string((a-'0')*(b-'0'));
}
string solution(string a, string b, string op){
return op == "+" ? to_string(stoi(a)+stoi(b)) : op == "-" ? to_string(stoi(a)-stoi(b)) : to_string(stoi(a)*stoi(b));
}
int solution(int a, string b, string op){
return op == "+" ? a+stoi(b) : op == "-" ? a-stoi(b) : a*stoi(b);
}
string tostring(char c){
switch (c){
case '0' : return "0";
case '1' : return "1";
case '2' : return "2";
case '3' : return "3";
case '4' : return "4";
case '5' : return "5";
case '6' : return "6";
case '7' : return "7";
case '8' : return "8";
case '9' : return "9";
case '+' : return "+";
case '-' : return "-";
case '*' : return "*";
}
}
void calc(){
vector<string> ns, nss;
for(int i = 0; i < len; ++i) {
if (garo[i]) ns.emplace_back(solution(str[i], str[i + 2], str[i + 1])), i += 2;
else ns.emplace_back(tostring(str[i]));
}
nss.emplace_back(ns[0].c_str());
for(int i = 1; i < ns.size(); ++i){
if(ns[i]=="*") nss.emplace_back(solution(nss.back(),ns[i+1],ns[i])),nss.erase(nss.end()-2), ++i;
else nss.emplace_back(ns[i].c_str());
}
int ret = stoi(nss[0]);
for(int i = 1; i < nss.size(); i+=2){
ret = solution(ret,nss[i+1],nss[i]);
}
if(ans.first) ans.second = max(ans.second,ret);
else ans.second = ret, ans.first = true;
}
void DFS(int cur){
if(cur+1>=len){
calc();
return;
}
garo[cur] = true;
DFS(cur+4);
garo[cur] = false;
DFS(cur+2);
}
int main(){
ans.first = false, ans.second = 0;
cin>>len>>str;
DFS(0);
cout<<ans.second;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/BOJ/16638/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.