题目链接
题意
给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b。中位数是指把所有元素从小到大排列后,位于中间的数。
思路
- 求连续子序列的中位数为b,则此序列中大于b的数目=小于b的数目,因此标记大于b的数字为1,小于b的数字为-1,找到b的位置
- 然后利用前缀和,左边的数字和+右边的数字和=0为一种答案,若左边或者右边的数字和为0,答案需要额外加1,因为此时表示从该位置到b的位置符合条件
- 注意单独一个b也符合条件
参考代码
#include<bits/stdc++.h>
using namespace std;
int n,b,aa[1000100];
int t=10000;
int num[1000100];
int main()
{
cin>>n>>b;
int pos=0,ans=0;
int tmp;
for(int i=0; i<n; i++)
{
cin>>tmp;
if(tmp==b)
{
pos=i;
aa[i]=0;
}
else if(tmp<b)
aa[i]=-1;
else
aa[i]=1;
}
int tmp1=0;
for(int i=pos-1; i>=0; i--)
{
tmp1+=aa[i];
num[tmp1+10000]++;
if(tmp1==0)
ans++;
}
tmp1=0;
for(int i=pos+1; i<n; i++)
{
tmp1+=aa[i];
ans+=num[10000-tmp1];
if(tmp1==0)
ans++;
}
cout<<ans+1<<endl;
}