P10303 [THUWC 2020] 报告顺序 题解
给你
n 个三元组(a,b,c) ,每次操作可以把x 变为a|x|+bx+c ,你可以任意排列这n 个三元组。问你在一个给定的初始的
x 下,能得到最终的最大x 的值是多少。数据规模n,|a|,|b|,|c|,|s|\le 15 。
看到
- 当
x\ge 0 时,操作即为x\leftarrow (a+b)x+c 。 - 否则操作即为
x\leftarrow (b-a)x+c 。
一个暴力
不难想到
子任务 2
如果有
那么我们只需要关心四个值:使用过一些三元组过后的
结合刚刚的分析,我们设出状压 DP 状态为
然后直接 DP,转移是容易的。
拓展到 c_i\neq 0
分析刚刚那个做法不再适用的原因:可能有一些时候,
不过我们注意到
然后发现这部分只有
实现部分参考了一下 GD 队长的做法,他的写法非常的清晰!
#include <bits/stdc++.h>
#define int long long
#define i128 __int128
#define r(x) for (int i = 1; i <= x; i++)
#define re(i, x) for (int i = 1; i <= x; i++)
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define reb(i, a, b) for (int i = a; i >= b; i--)
using namespace std;
const int N = (1 << 16) + 5, M = 18, V = 250;
const i128 inf = 1e38;
int n, s, a[M], b[M], c[M], flag[N][4];
i128 f[N][4];
bitset<505> bs[N];
void chmax(i128 &x, i128 y) { x = max(x, y); }
void chmin(i128 &x, i128 y) { x = min(x, y); }
i128 myabs(i128 x) { return x > 0 ? x : -x; }
i128 funt(i128 x, int a, int b, int c) {
return a * myabs(x) + b * x + c;
}
void write(i128 x)
{
if (!x) return cout << "0\n", void();
stack<int> s; if (x < 0) cout << "-", x = -x;
while (x) s.push(x % 10), x /= 10;
while (!s.empty()) cout << s.top(), s.pop();
}
signed main()
{
cin.tie(0)->sync_with_stdio(0);
cin >> n >> s, bs[0][s + V] = 1;
r(n) cin >> a[i] >> b[i] >> c[i];
rep(S, 0, (1 << n) - 1)
{
f[S][0] = 0, f[S][1] = inf;
f[S][2] = -inf, f[S][3] = 0;
}
if (s >= 0) f[0][0] = f[0][1] = s;
else f[0][2] = f[0][3] = s;
rep(S, 0, (1 << n) - 1)
{
vector<i128> v;
if (f[S][0] >= f[S][1])
{ // 确保有值再进行转移
v.push_back(f[S][0]);
v.push_back(f[S][1]);
}
if (f[S][2] >= f[S][3])
{
v.push_back(f[S][2]);
v.push_back(f[S][3]);
}
rep(j, -V, V) if (bs[S][j + V])
v.push_back(j);
if (S == (1 << n) - 1)
return write(*max_element(v.begin(), v.end())), 0;
rep(j, 1, n)
{
if ((S >> (j - 1)) & 1) continue;
int nS = S + (1 << (j - 1));
for (auto val : v)
{
i128 w = funt(val, a[j], b[j], c[j]);
if (w >= 0) chmax(f[nS][0], w), chmin(f[nS][1], w);
else chmax(f[nS][2], w), chmin(f[nS][3], w);
if (-V <= w && w <= V) bs[nS][w + V] = 1;
}
}
}
return 0;
}