经典套路:二分中位数
check中求<=mid的数量
若<=mid的数量 >= 中位数的定义数量,则中位数一定<=mid,r=mid
反之,中位数一定>mid,l=mid
最后答案即为r
那么思考一下check中如何求<=mid的数量?先通过A数组求B数组,再通过B数组求C数组中<=mid的数量
举例说明:
若A数组是 1 3 1 7 , 假设此时二分的mid = 1
那么B数组即为
1 1 1 1
3 1 3
1 1
7
C数组即为
1 1 1 1
3 1 1
1 1
7
C数组中<=mid的数量即为7
但因为我们要求的是<=mid的数量,所以实际并不需要真的求出B、C数组,只需要知道C数组某个数是否<=mid即可
还是这个例子,那么首先将A数组<=mid的元素赋为1,反之为0
A数组即为 1 0 1 0
对A做前缀和 1 1 2 2 ,即可n方求出B数组
那么B数组即为
1 1 1 1
0 1 0
1 1
0
同理对B数组做前缀和也能 n方求出C数组
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define all(x) x.begin(),x.end()
#define no cout<<"No"<<endl
#define yes cout<<"Yes"<<endl
#define endl '\n'
// #define x first
// #define y second
typedef pair<int,int> PII;
const int N=2010;
const int mod=998244353;
const int INF=0x3f3f3f3f3f3f3f3f;
int b[N][N];
void solve(){
int n;cin>>n;
vector<int>a(n+1);
for(int i=1;i<=n;i++){
cin>>a[i];
}
vector<int>pre(n+1);
auto check=[&](int mid){
for(int i=1;i<=n;i++)pre[i]=pre[i-1]+(a[i]<=mid?1:0);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
b[i][j]=0;
}
}
for(int l=1;l<=n;l++){
for(int r=l;r<=n;r++){
if(pre[r]-pre[l-1]>=(r-l+2)/2)b[l][r]=1;
else b[l][r]=0;
}
}
for(int i=n;i>=1;i--){
for(int j=i;j>=1;j--){
b[j][i]+=b[j+1][i];
}
}
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
b[i][j]+=b[i][j-1];
}
}
int cnt=0;
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
if(b[i][j]>=((j-i+2)*(j-i+1)/2+1)/2)cnt++;
}
}
if(cnt>=(n*n/2+1)/2)return 1;
return 0;
};
int l=0,r=1e9;
while(l+1!=r){
int mid=l+r>>1;
if(check(mid))r=mid;
else l=mid;
}
cout<<r<<endl;
}
signed main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int _=1;
while(_--)solve();
return 0;
}