题解:由于题目已经提示我们这是个单峰函数,所以很容易想到三分法,所以我们就枚举中位数,为保证平均数最大,左右两侧都从右往左取数。
代码如下:
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #define MN 100005 5 using namespace std; 6 int n,a[MN],maxl,l,r,lm,rm; 7 long long sum[MN]; 8 double ans=-100000; 9 int main() 10 { 11 freopen("win.in","r",stdin); 12 freopen("win.out","w",stdout); 13 scanf("%d",&n); 14 for(int i=1;i<=n;i++) scanf("%d",&a[i]); 15 sort(a+1,a+1+n); 16 for(int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i]; 17 double la=a[1],ra=a[1]; 18 for(int i=1;i<=n;i++){ 19 maxl=min(i-1,n-i); maxl=max(0,maxl); 20 l=0; r=maxl; 21 while(l<r-1){//l、r中隔1为a[i]的位置 22 lm=l+(r-l)/3; rm=r-(r-l)/3; 23 la=(double)(sum[i-1]-sum[i-lm-1]+sum[n]-sum[n-lm]+a[i])/(double)(lm*2+1); 24 ra=(double)(sum[i-1]-sum[i-rm-1]+sum[n]-sum[n-rm]+a[i])/(double)(rm*2+1); 25 if(la<ra) l=lm+1; 26 else r=rm-1; 27 } 28 la=(double)(sum[i-1]-sum[i-l-1]+sum[n]-sum[n-l]+a[i])/(double)(l*2+1); 29 ra=(double)(sum[i-1]-sum[i-r-1]+sum[n]-sum[n-r]+a[i])/(double)(r*2+1); 30 if(la<ra) ans=max(ans,ra-(double)a[i]); 31 else ans=max(ans,la-(double)a[i]); 32 } 33 printf("%.2lf",ans); 34 }
时间: 2024-10-14 17:46:29