跳到正文

题解

[AGC025C] Interval Game 题解

bugmaker3243约 5 分钟
原文
文章信息与版本

文章信息

发布
2022年10月10日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

基本分析

AA 的决策是很简单的,如果 AA 当前在 pospos,需要前往 (l,r)(l,r),因为 AA 要使自己的路程最小,则有以下三种情况:

  • pospos 在 (l,r)(l,r) 左侧,即 pos<lpos<l,则 AA 会前往 ll。
  • pospos 在 (l,r)(l,r) 上,即 l≤pos≤rl\leq pos\leq r,则 AA 不会动。
  • pospos 在 (l,r)(l,r) 右侧,即 r<posr<pos,则 AA 会前往 rr。

这种走法是一种贪心的走法。

正确性证明

假如 pospos 在 (l,r)(l,r) 上,那么不动最优是显然的,你又不可能减少答案吧。

于是不妨设 pos<lpos<l,即 pospos 在 (l,r)(l,r) 左侧(右侧证明同理),那么 AA 这一步会向右走,代价为 l−posl-pos。

考虑反证法,如果 AA 走到另一个位置 xx(l≤x≤rl\leq x\leq r),那么接下来这一步有两种情况:

  • 向左走到 yy,到 ll 总代价为 l−pos+l−y=2l−pos−yl-pos+l-y=2l-pos-y,到 xx 总代价为 x−pos+x−y=2x−pos−yx-pos+x-y=2x-pos-y,由于 l≤xl\leq x,所以 2l−pos−y≤2x−pos−y2l-pos-y \leq 2x-pos-y

  • 向右走到 yy,到 ll 总代价为 l−pos+y−l=y−posl-pos+y-l=y-pos,到 xx 总代价为 x−pos+y−x=y−posx-pos+y-x=y-pos,二者相等。

综上,到 ll 一定比到 xx 更优。

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

  • 如果当前这一步向左走,那么 BB 会选择 rr 最小的区间使 AA 走的多。

  • 如果当前这一步向右走,那么 BB 会选择 ll 最大的区间使 AA 走的多。

具体实现

维护变量 nownow 和两个堆 lheaplheap 和 rheaprheap 分别维护 ll 的最大值和 rr 的最小值。

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

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

代码(请勿抄袭)

C++
#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;
}
原文
存档评论3 条抓取于