题目分析
一开始想的是普通的贪心,就是每次都走尽可能更优的路线,后来被样例肘击了。
后来发现有减号和除号,就导致前一步的最大值可能在这一步就不对了。所以我们反其道而行之,遇到减号和除号的时候就用上一步的最小值,这样在过一扇门的时候会产生 种结果:
- 用上一步的最大值走第一扇门。
- 用上一步的最大值走第二扇门。
- 用上一步的最小值走第一扇门。
- 用上一步的最小值走第二扇门。
把这 种情况分别取最大值和最小值存起来,最后输出最大值就行了。
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e4 + 5;
int maxn[N],minn[N];
int calc(int x,string a,string op,string b){
int num;
if (a == "x") num = stoll(b);
else num = stoll(a);
if (op == "+") return x + num;
if (op == "-"){
if (a == "x") return x - num;
else return num - x;
}
if (op == "*") return x * num;
if (op == "/"){
if (a == "x") return x / num;
else return num / x;
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int t;
cin >> t;
while (t--){
int n,x;
cin >> n >> x;
maxn[0] = minn[0] = x;
for (int i = 1;i <= n;i++){
string a1,op1,b1,a2,op2,b2;
cin >> a1 >> op1 >> b1 >> a2 >> op2 >> b2;
maxn[i] = max({calc(maxn[i - 1],a1,op1,b1),calc(minn[i - 1],a1,op1,b1),calc(maxn[i - 1],a2,op2,b2),calc(minn[i - 1],a2,op2,b2)});
minn[i] = min({calc(maxn[i - 1],a1,op1,b1),calc(minn[i - 1],a1,op1,b1),calc(maxn[i - 1],a2,op2,b2),calc(minn[i - 1],a2,op2,b2)});
}
cout << maxn[n] << '\n';
}
return 0;
}