[AGC025C] Interval Game 题解
bugmaker3243 · · 题解
基本分析
- 向右走到
y ,到l 总代价为l-pos+y-l=y-pos ,到x 总代价为x-pos+y-x=y-pos ,二者相等。
综上,到
而
-
如果当前这一步向左走,那么
B 会选择r 最小的区间使A 走的多。 -
如果当前这一步向右走,那么
B 会选择l 最大的区间使A 走的多。
具体实现
维护变量
每次取出第一个没有用过的区间,计算代价并标记,更新
注意第一步有两种选择:向右或向左。只需两种都计算一遍并取大的就可以了。
代码(请勿抄袭)
#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;
}