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