1303: [CQOI2009]中位数图
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 1541 Solved: 1003
[Submit][Status][Discuss]
Description
给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b。中位数是指把所有元素从小到大排列后,位于中间的数。
Input
第一行为两个正整数n和b ,第二行为1~n 的排列。
Output
输出一个整数,即中位数为b的连续子序列个数。
Sample Input
7 4
5 7 2 4 3 1 6
5 7 2 4 3 1 6
Sample Output
4
HINT
第三个样例解释:{4}, {7,2,4}, {5,7,2,4,3}和{5,7,2,4,3,1,6}
N<=100000
统计左右 比b小 和比b大的数的个数就好辣!
#include<iostream>
#include<cstdio>
using namespace std;
const int common=100005;
int n,b,a[100005],lef[200105],rig[200105];
int main()
{
int pos=0;
scanf("%d%d",&n,&b);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]==b)
pos=i;
}
int sum=0;
lef[common]=rig[common]=1;
for(int i=pos-1;i>=1;i--)
{
if(a[i]>b)
sum++;
else
sum--;
lef[sum+common]++;
}
sum=0;
for(int i=pos+1;i<=n;i++)
{
if(a[i]<b)
sum++;
else
sum--;
rig[sum+common]++;
}
int ans=0;
for(int i=common-n;i<=common+n;i++)
ans+=lef[i]*rig[i];
printf("%d\n",ans);
return 0;
}