排一遍序然后用l,r指针进行移动,每次移动的是靠1,或靠n更近的那个指针
#include<bits/stdc++.h> using namespace std; typedef long long ll; int a[100200]; int main() { int n; ll k; scanf("%d%lld",&n,&k); for(int i=0;i<n;i++) scanf("%d",&a[i]); sort(a,a+n); int minn=a[0],maxx=a[n-1]; int l=0,r=n-1; while(minn!=maxx&&k>0) { ll len1=0,len2=0; while(a[l]==minn) l++; len1=l; while(a[r]==maxx) r--; len2=n-1-r; if(len1<=len2) { ll w=a[l]-minn; if(w*len1<=k) { minn=a[l]; k-=w*len1; } else { minn=minn+k/len1; break; } } else { ll w=maxx-a[r]; if(w*len2<=k) { maxx=a[r]; k-=w*len2; } else { maxx=maxx-k/len2; break; } } } int q=maxx-minn; printf("%d ",q); return 0; }
ps:这题自己还开了个桶来做,并且开了桶的做法不知道为什么错在大的数据。。