P14112 [ZJCPC 2017] Sequence to Sequence
EuphoricStar · · 题解
线性规划对偶。模拟赛屡次被这东西爆了,遂学习。
以下令
首先做一些基本的观察:
- 对于
a_i = 0 ,若b_i \ne 0 则无解,否则一定有解。 -
- 所以我们的操作顺序应该是,先进行若干次
- 操作,使得所有b_i = 0 的位置都变成0 ,且所有b_i \ne 0 的位置都仍然\ge 1 。然后再进行若干次+ 操作,再进行若干次- 操作,此时所有a_i = b_i 。 - 这么做的正确性是,我们不会在第一步减到一半再去加别的受影响的元素,因为这样可以替换成两个不交的操作。
考虑写成线性规划的形式。对于一个区间
那么:
我们严格按照在 OI 中更易上手的线性规划对偶中的步骤进行对偶。
首先将所有约束变成
然后对三种约束设一个变量
将这个式子整理成以
给
假设这个线性规划有整数最优解,然后观察一下约束。
首先显然
然后连续的两个非零
然后我们还要求,假设
发现
所以我们有
接下来可以 DP。设
时间复杂度
#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;
const int maxn = 100100;
ll n, a[maxn], b[maxn], c[maxn], d[maxn], f[2][2][3];
void solve() {
scanf("%lld", &n);
for (int i = 1; i <= n; ++i) {
scanf("%lld", &a[i]);
}
for (int i = 1; i <= n; ++i) {
scanf("%lld", &b[i]);
}
for (int i = 1; i <= n; ++i) {
if (!a[i] && b[i]) {
puts("-1");
return;
}
}
mems(f, -0x3f);
int o = 0;
f[0][0][1] = 0;
for (int i = 1; i <= n; ++i) {
o ^= 1;
mems(f[o], -0x3f);
for (int x = 0; x <= 1; ++x) {
for (int y = 0; y <= 2; ++y) {
ll v = f[o ^ 1][x][y];
if (v < -1e18) {
continue;
}
if (b[i]) {
for (int p = 0; p <= 2; ++p) {
for (int q = -1; q <= 1; ++q) {
if ((q && q + 1 == y) || x + q - p > 1) {
continue;
}
int nx = max(x + q - p, 0), ny = (q ? q + 1 : y);
f[o][nx][ny] = max(f[o][nx][ny], v + p * (1 - a[i]) + q * (a[i] - b[i]));
}
}
} else {
for (int r = 0; r <= 1; ++r) {
if (x + r > 1) {
continue;
}
f[o][x + r][y] = max(f[o][x + r][y], v + r * a[i]);
}
}
}
}
}
ll ans = -1e18;
for (int i = 0; i <= 1; ++i) {
for (int j = 0; j <= 2; ++j) {
ans = max(ans, f[o][i][j]);
}
}
printf("%lld\n", ans);
}
int main() {
int T = 1;
scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}