题解 AT3949 【[AGC022D] Shopping】

· · 题解

标签: 神奇性质.

Part 1

先可以把 \lfloor {t_i\over 2L}\rfloor 加入答案, 然后把 t_i 模上 2L , 这样答案显然不变, 并且可以使 t_i<2L.

由于最终要回到 0 处, 跑的路程必定是 2L 的整数倍, 所以我们只需要求火车最少跑多少来回即可(记为 ans).

Part 2

首先我们给答案确定一个上界并构造方案.

我们先走到商场 1 , 停留 2L 后必然购物完, 且火车恰好经过, 那么乘上火车到下一个商场, 反复这么做, 直到在第 n 个商场购物完后就回到 0 . 这样的答案是 n+1 .

考虑优化方案以达到最优.

我们设 l_i 表示从左边到 i, 列车下次(从右边)经过 i 的时候是否购完物. 类似定义 r_i . 显然 l_i=[2(L-x_i)\geqslant t_i],r_i=[2x_i\geqslant t_i].

显然对于 l=r=0 的点, 只能在商场 i 停留 2L 所以没有优化的余地.

若存在一组 i,j 满足 i<j,r_i=l_j=1 , 我们对原方案进行修改: 在从商场 i-1 到商场 i 的过程中间先走完商场 j , 那么这样路程不会变多. 我们白嫖了这个商场 j . 所以可以把这样 i, j 匹配起来, 那么答案就减少最大的匹配数.

另外我们发现对于 l=1,r=0 的商场有 2(L-x)\geqslant t,2x\leqslant t , 可得 x\leqslant \min\{\frac t2,L-\frac t2\}\leqslant\frac L2. 同理对于 r=1,l=0 的商场有 x\geqslant \frac L2 , 故这两种点不可能匹配起来.

那么我们用 l=r=1 和上述两种点尽量匹配, 剩余的再两个两个匹配就好了.

另外, 若 l_n=1 , 我们在商场不需要等 2L , 火车从右边经过时直接上车就好了.

本题有许多细节(可能有的上面都没有提到, 譬如商场 n 是不会被白嫖的等), 需要考虑清楚.

时间复杂度 O(n).

#include <bits/stdc++.h>
using namespace std;
int read();
int n, L, res;
int x[300005], t[300005], del[300005];
int l[300005], r[300005];
int main() {
    n = read(), L = read(), res = n + 1;
    for (int i = 1; i <= n; ++i) x[i] = read();
    for (int i = 1; i <= n; ++i)
        res += (t[i] = read()) / (L << 1), t[i] %= L << 1;
    for (int i = 1; i <= n; ++i) {
        if (!t[i]) {
            --res, del[i] = 1;
            continue;
        }
        del[i] = !((l[i] = 2 * (L - x[i]) >= t[i]) | (r[i] = 2 * x[i] >= t[i]));
    }

    res -= l[n];
    int sum = 0, top = 0, pos = n;
    for (int i = 1; i < n; ++i) {
        if (del[i]) continue;
        if (!l[i]) {
            pos = i;
            break;
        }
        r[i] ? ++top : (top ? --top, --res : 0);
    }

    sum += top, top = 0;
    for (int i = n - 1; i >= pos; --i) {
        if (del[i]) continue;
        if (!r[i]) break;
        l[i] ? ++top : (top ? --top, --res : 0);
    }
    printf("%lld\n", 2ll * L * (res -= sum + top >> 1));
    return 0;
}
const int _SIZE = 1 << 22;
char ibuf[_SIZE], *iS = ibuf, *iT = ibuf;
#define gc                                                         \
    (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), \
     (iS == iT ? EOF : *iS++) : *iS++)
int read() {
    int x = 0, f = 1;
    char c = gc;
    while (!isdigit(c)) f = (c == '-') ? -1 : f, c = gc;
    while (isdigit(c)) x = x * 10 + c - '0', c = gc;
    return x * f;
}