跳到正文

题解

题解:AT_abc471_c [ABC471C] Cookies and Greedy Takahashi

Sum_Fpy约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月16日
收录
2026年8月24日
更新
2026年8月24日
篇幅
约 2 分钟
获赞
2

版本

  1. v1当前

考虑用一个 set,把这些数全塞进去,假如我们当前在 xx,那么我们直接找大于 xx 最近的数和小于等于 xx 最近的数,直接在 set 上二分找到,然后直接选两者中距离更小的,把他删掉就行了。貌似思路和之前某一场的 D 重了?

代码

C++
#include<bits/stdc++.h>
#define ll long long
#define il inline
using namespace std;
#define rep(x,l,r) for(register int x=l;x<=r;++x)
#define per(x,l,r) for(register int x=l;x>=r;--x)
#define inf INT_MAX
#define linf LLONG_MAX
il ll read(){
	ll k=0,f=1;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){k=(k<<1)+(k<<3)+(c^48);c=getchar();}return f*k;}
int n;
int main(){
	n=read();
	set<ll>s;
	rep(i,1,n) s.insert(read());
	ll p=0,ans=0;
	while(!s.empty()){
		auto it=s.upper_bound(p);
		ll c1=linf,c2=linf;
		if(it!=s.end())c1=*it;
		if(it!=s.begin())c2=*prev(it);
		ll d1=abs(c1-p),d2=abs(c2-p);
		ll ch;
		if(d1<d2)ch=c1;
		else if(d2<d1)ch=c2;
		else ch=min(c1,c2);
		ans+=abs(ch-p);
		p=ch;
		s.erase(s.find(ch));
	}
	printf("%lld\n",ans);
	return 0;
}
原文