由于序列有序,求其中一个最优解,二分答案即可,注意二分时上边界满足才保存
#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> #define ll long long using namespace std; const int maxx = 300005; ll a[maxx]; ll l,r; ll pre[maxx]; int main() { int t; ll ans=0; ll n; scanf("%d",&t); while(t--) { ans=0; scanf("%lld",&n); for (int i=1; i<=n; i++) { scanf("%lld",&a[i]); } sort(a+1,a+1+n); ll r=100000000; ll l=0; ll mid=0; ll pr=0,ba=0; while(l<=r) { pr=0; ba=0; mid=(l+r)/2; for (int i=1; i<=n; i++) { if (a[i]<mid) { pr+=(mid-a[i]);//左边和 } else if (a[i]>mid) { ba+=((a[i]-mid)/2);//右边和 } } if (ba>=pr){//如果满足条件答案才被记录下来 ans=mid; l=mid+1; continue; }else { r=mid-1;//不满足就继续向上查找 continue; } } printf("%lld ",ans); } return 0; }