题解 P4801 【[CCO 2015]饥饿的狐狸】

· · 题解

(体验党看 博客)

贪心。

观察题目,我们不难发现,要得到最大美味值,狐狸应该先交错吃温度最大的和最小的饼干,其中如果能喝冰水或开水就更好了。所以我们给所有饼干按照温度排序,交替选择左右端点吃,如果先喝水再吃能获得更大美味值就更好啦。这样最大美味值就求出来啦。(注意左右端点谁先开始,可能得到两个答案,再取个 max。)

那么最小美味值呢?我们肯定按照温度顺序吃饼干。这样每两个饼干之间的差值就是美味度。比如我们记第 i 个饼干和 i-1 个饼干的差值为 T_i-T_{i-1},则第 i+1 个饼干和 i 个饼干的差值为 T_{i+1}-T_i,我们容易得到:如果不喝水,差值即为 T_n-T_1。此时即可分类讨论:

(1) 如果水温度在 [T_1,T_n] 之间,喝水与不喝水,对答案没有影响,答案就是 T_n-T_1。(想一想,为什么?)

(2) 如果水温度小于 T_1,我们又必须要喝水,答案再加上 W-T_1,即为 T_n-W。

(3) 同理如果水温大于 T_n,答案即为 W-T_1。

合并以上算式我们可以得到一句富有亲和力的算式 \text{MinAns}=\max\{W-T_1,0\}+\max\{T_n-W,0\}.

真漂亮啊……

以下是代码,已经无需赘言:

/* [CCO2015] 饥饿的狐狸
 * Au: GG
 */
#include <cstdio>
#include <algorithm>
using namespace std;
#define ll long long

int n, w; ll d[100003], anl, anh1, anh2;

int main() {
    scanf("%d%d", &n, &w);
    for (int i=1; i<=n; ++i) scanf("%lld", &d[i]);
    sort(d+1, d+n+1);
    anl=max(0ll, w-d[1])+max(0ll, d[n]-w);
    ll las=w, l=1ll, r=n;
    for (int i=1; i<=n; ++i) {
        if (i&1) anh1+=max(abs(d[l]-w), abs(d[l]-las)), las=d[l++];
        else anh1+=max(abs(d[r]-w), abs(d[r]-las)), las=d[r--];
    }
    las=w, l=1ll, r=n;
    for (int i=1; i<=n; ++i) {
        if (i&1) anh2+=max(abs(d[r]-w), abs(d[r]-las)), las=d[r--];
        else anh2+=max(abs(d[l]-w), abs(d[l]-las)), las=d[l++];
    }
    printf("%lld %lld\n", anl, max(anh1, anh2));
    return 0;   
}

另外说一句,没必要滥用氧气优化,因为本题 真 没有省选难度……