其实只需要把样例一加进去就行了,这个代码样例1没过但是100分
#include<bits/stdc++.h>
#define int long long
using namespace std ;
int n , temp[512345] , a[512345] , b[512345] , cnt=0 , ans[512345] ;
map<int,int> mp ;
void solve(int l,int r,int L,int R){
if(l==r||L>R) return ;
int mid=(l+r)>>1 , sum=0 , maxn=0 , tot=L-1 ;
for(int i=L;i<=R;i++) sum += abs(a[i]-b[mid+1]) ;
maxn = sum ;
for(int i=L;i<=R;i++){
sum -= abs(a[i]-b[mid+1]) ;
sum += abs(a[i]-b[mid]) ;
if(sum<maxn){
maxn = sum ;
tot = i ;
}
}
for(int i=L;i<=tot;i++) ans[i] = mid ;
solve(l,mid,L,tot) ;
solve(mid+1,r,tot+1,R) ;
}
signed main(){
cin >> n ;
for(int i=1;i<=n;i++) scanf("%lld",a+i) , temp[i] = a[i] ;
sort(temp+1,temp+1+n) ;
for(int i=1;i<=n;i++){
while(temp[i]==temp[i+1]&&i<n) i++ ;
mp[temp[i+1]] = ++cnt ;
b[cnt] = temp[i] ;
}
solve(1,cnt,1,n) ;
int thing=0 ;
for(int i=1;i<=n;i++)
thing += abs(a[i]-b[ans[i]]) ;
cout << thing ;
return 0;
}