跳到正文

题解

题解:P16440 [XJTUPC 2026] 公式战士

super_peach约 3 分钟
原文

这是 2026年5月12日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年5月12日
收录
2026年5月12日
更新
2026年9月9日
篇幅
约 3 分钟
题目
P16440

版本

  1. v2当前
  2. v1

题目分析

一开始想的是普通的贪心,就是每次都走尽可能更优的路线,后来被样例肘击了。

后来发现有减号和除号,就导致前一步的最大值可能在这一步就不对了。所以我们反其道而行之,遇到减号和除号的时候就用上一步的最小值,这样在过一扇门的时候会产生 44 种结果:

  • 用上一步的最大值走第一扇门。
  • 用上一步的最大值走第二扇门。
  • 用上一步的最小值走第一扇门。
  • 用上一步的最小值走第二扇门。

把这 44 种情况分别取最大值和最小值存起来,最后输出最大值就行了。

C++
#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;
}