题解 | #[CQOI2009]中位数图#
[CQOI2009]中位数图
https://ac.nowcoder.com/acm/problem/19913
把小于b的数置为-1,大于0的数置为1,再从b位置开始,向两边求前缀和(分为两个数组;ps:这里因为有负数,所以我开了四个数组) 然后哈希,将前缀和的值映射到数组中,之后,我们再去找左右两边找相反数,将相反数的个数直接乘起来,单独再加上左右两边的0的数量 最后,再加一,因为仅一个b也是可以的
```#include <bits/stdc++.h>
#define int long long
using namespace std;
int a[100005];
int hh[200005];
int xx[200005];
int h[200005];
int x[200005];
void solve(){
int n;
cin>>n;
int b;
cin>>b;
int tt;
int index=0;
for(int i=1;i<=n;i++){
cin>>a[i];
if(a[i]<b){
a[i]=-1;
}
if(a[i]==b){
a[i]=0;
index=i;
}
if(a[i]>b){
a[i]=1;
}
}
int temp=0;
for(int i=index-1;i>=1;i--){
temp+=a[i];
if(temp<0){
h[abs(temp)]++;
}
else{
hh[temp]++;
}
}
temp=0;
for(int i=index+1;i<=n;i++){
temp+=a[i];
if(temp<0){
x[abs(temp)]++;
}
else{
xx[temp]++;
}
}
int ans=0;
ans+=hh[0]*xx[0];
ans+=hh[0];
ans+=xx[0];
for(int i=1;i<=100000;i++){
ans+=hh[i]*x[i];
ans+=h[i]*xx[i];
}
cout<<++ans<<endl;
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;
//cin>>t;
t=1;
while(t--){
solve();
}
return 0;
}