A02 选择运算
初始数为0,每次2个+ - * / 的操作,选择一个,最后得到的数要最大。
样例输入:
3 +1 *3 +2 *40 -3 /2
样例输出:
37
代码:字符串的处理+dfs(依旧参考了很多别人的答案,自己做的时候也用到了dfs,但是部分测试用例通过不了)
#include<iostream> #include<cstdio> #include<string> #include<vector> #include<algorithm> using namespace std; int calc(int x, int y, char op) { if (op == '+') return x + y; if (op == '-') return x - y; if (op == '*') return x * y; if (op == '/') return x / y; return 0; } int n; vector<int> na; vector<int> nb; vector<char> oa; vector<char> ob; const int INF = 0xfffffff; int ans = -INF; void dfs(int num, int id) { if (id == n) { ans = max(ans, num); return; } int t = calc(num, na[id], oa[id]); dfs(t, id + 1); t = calc(num, nb[id], ob[id]); dfs(t, id + 1); } int main() { int i; int opnd1=0, opnd2=0; scanf("%d", &n); string a, b; for (i = 0; i < n; i++) { cin >> a >> b; if (a.size() == 2) { opnd1 = a[1] - '0'; } else{ opnd1 = (a[1] - '0') * 10 + (a[2] - '0'); } na.push_back(opnd1); oa.push_back(a[0]); if (b.size() == 2) { opnd2 = b[1] - '0'; } else { opnd2 = (b[1] - '0') * 10 + (b[2] - '0'); } nb.push_back(opnd2); ob.push_back(b[0]); } dfs(0, 0); printf("%d\n", ans); return 0; }