P2286 [HNOI2004] 宠物收养场 题解

P2286 [HNOI2004] 宠物收养场 set做法

题链\(_{洛谷}\) \(_{题库}\)

思路

一眼查找前驱后继的题。注意到一句话:

image

那么用 set 就没有什么阻碍了,方便又快捷。

题意很简单,若宠物多则查找与人需求最接近的上下两个值,人多则找与宠物最接近的上下两个人的值。出题人很善良,把选人和选宠物的标准定成一样的,这样我们只写一个平衡树就可以了。

但不想写平衡树而 vector 的时间开销很大,那么我们考虑 set(不会 set 的看这里),set 是以红黑树的形式实现的,速度要快不少。

操作很简单,如果来的人(或宠物)与当前余下的同类就插入 set,如果 set 空了就改变余下的类型并插入,若不同类就进行查找,只用到迭代器 set<int>::iteratorlower_bound 查找操作。

code:

#include<bits/stdc++.h>
using namespace std;
const int Ratio=0;
const int maxx=2147483647;
int n,ans,lx;
set<int>s;
namespace Wisadel
{
	void Wfind(int x)
	{
		set<int>::iterator l,r;
		l=--s.lower_bound(x),r=s.lower_bound(x);
		if(x-*l<=*r-x&&*l!=-maxx) ans+=x-*l,s.erase(l);
		else ans+=*r-x,s.erase(r);
		//查找 更新答案
		ans%=1000000;
	}
	short main()
	{
		scanf("%d",&n);
		s.insert(-maxx),s.insert(maxx);//防止越界
		for(int i=1;i<=n;i++)
		{
			int a,b;
			scanf("%d%d",&a,&b);
			if(s.size()==2) lx=a,s.insert(b);
			else if(lx==a) s.insert(b);
			else Wfind(b);
		}
		printf("%d\n",ans);
		return Ratio;
	}
}
int main(){return Wisadel::main();}

完结撒花~

posted @ 2024-07-04 11:40  DrRatio  阅读(12)  评论(1编辑  收藏  举报