Median on Segments (General Case Edition)題解
阿新 • • 發佈:2019-01-25
連div3的題都不會寫了。。。。
題意簡單來說就是給你一串數字,求有多少個區間,使得區間內的數字排序後中位數恰好是m。
題解的做法是先找出所有滿足中位數大於等於m的區間,然後減去滿足中位數大於等於m+1的區間,就可以得到中位數為m的區間數了。
如何統計中位數大於等於m的區間?必須滿足區間內不小於m的數值的數量>小於m的數值的數量。於是我們可以使用預處理出noless-less的字首和k,那麼對於一個右端點j,滿足的左端點i僅需滿足pre[i]
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2*1e5+15;
const int maxm=1005;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
int n,m;
int a[maxn];
ll calc(int val){
vector<int> vec(2*n+1);
vec[n]=1;
ll sum=n;
ll add=0;
ll ans=0;
for(int i=0;i<n;i++){
if(a[i]<val){
sum--;
add-=vec[sum];
}
else {
add+=vec[sum];
sum++;
}
ans+=add;
vec[sum]++;
}
return ans;
}
int main(){
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
ll ans=calc(m)-calc(m+1);
printf("%lld\n",ans);
return 0;
}