[AGC025C] Interval Game 题解

· · 题解

基本分析

- $pos$ 在 $(l,r)$ 左侧,即 $pos<l$,则 $A$ 会前往 $l$。 - $pos$ 在 $(l,r)$ 上,即 $l\leq pos\leq r$,则 $A$ 不会动。 - $pos$ 在 $(l,r)$ 右侧,即 $r<pos$,则 $A$ 会前往 $r$。 这种走法是一种贪心的走法。 ### 正确性证明 假如 $pos$ 在 $(l,r)$ 上,那么不动最优是显然的,~~你又不可能减少答案吧~~。 于是不妨设 $pos<l$,即 $pos$ 在 $(l,r)$ 左侧(右侧证明同理),那么 $A$ 这一步会向右走,代价为 $l-pos$。 考虑反证法,如果 $A$ 走到另一个位置 $x$($l\leq x\leq r$),那么接下来这一步有两种情况: - 向左走到 $y$,到 $l$ 总代价为 $l-pos+l-y=2l-pos-y$,到 $x$ 总代价为 $x-pos+x-y=2x-pos-y$,由于 $l\leq x$,所以 $2l-pos-y \leq 2x-pos-y

综上,到 l 一定比到 x 更优。

而 B 为了让 A 走的更多,肯定会一左一右的选区间。

具体实现

维护变量 now 和两个堆 lheap 和 rheap 分别维护 l 的最大值和 r 的最小值。

每次取出第一个没有用过的区间,计算代价并标记,更新 now 的值。

注意第一步有两种选择:向右或向左。只需两种都计算一遍并取大的就可以了。

代码(请勿抄袭)

#include<bits/stdc++.h>
#define N 100005
#define P pair<int,int>
using namespace std;
int n,now,cnt,vst[N];
long long ans1,ans2;
struct node
{
    int l,r;
}a[N];
priority_queue<P>lheap;//维护最大l 
priority_queue<P,vector<P>,greater<P> >rheap;//维护最小r 
void init()//初始化 
{
    cnt=now=0;
    while(lheap.size()) lheap.pop();
    while(rheap.size()) rheap.pop();
    for(int i=1;i<=n;i++)
    {
        lheap.push(make_pair(a[i].l,i));
        rheap.push(make_pair(a[i].r,i));
        vst[i]=0;
    }
}
int findl()//向左走并计算代价 
{
    int res=0;
    int val=lheap.top().first,pos=lheap.top().second;
    lheap.pop();
    while(vst[pos]&&lheap.size()) val=lheap.top().first,pos=lheap.top().second,lheap.pop();
    //要一直找到第一个没有用过的区间 
    if(a[pos].l<=now&&now<=a[pos].r) return 0;//如果在里面就跳过计算 
    res=a[pos].l-now;//计算代价 
    now=a[pos].l;//更新now 
    vst[pos]=1;//打标记 
    return res;
}
int findr()//向右走并计算代价 
{
    int res=0;
    int val=rheap.top().first,pos=rheap.top().second;
    rheap.pop();
    while(vst[pos]&&rheap.size()) val=rheap.top().first,pos=rheap.top().second,rheap.pop();

    if(a[pos].l<=now&&now<=a[pos].r) return 0;
    res=now-a[pos].r;
    now=a[pos].r;
    vst[pos]=1;
    return res;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d %d",&a[i].l,&a[i].r);

    init();
    while(++cnt<=n)//第一步向左 
    {
        if(cnt&1) ans1+=findl();
        else ans1+=findr();
    }
    ans1+=abs(now);

    init();
    while(++cnt<=n)//第一步向右
    {
        if(cnt&1) ans2+=findr();
        else ans2+=findl();
    }
    ans2+=abs(now);
    printf("%lld",max(ans1,ans2));//两者取大的 
    return 0;
}