1303: [CQOI2009]中位数图
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 909 Solved: 581
[ Submit][ Status]
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
Source
【分析】:
输入时,将数列中所有小于中位数的数变为-1,所有大于中位数的数变为1,中位数变为0并记录中位数的位置。然后求从该位置向左端点求和,记录下每次和的数值,用计数排序方式记录每种数值的和出现的次数,同理,向右以相同方式进行。由于将原序列全转为了-1,0,1,因此和的范围为[-N,N],对于c语言,需将该范围强制转为[0,2N],实现详见程序
【代码】:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define MAXN 300010
int N,B,a[MAXN],where,ans=0,hash_left[MAXN],hash_right[MAXN];
void work()
{
int sumnow=N;
hash_left[N]=1;
for(int i=where-1;i>=1;i--)
{
sumnow+=a[i];
hash_left[sumnow]++;
}
sumnow=N;
hash_right[N]=1;
for(int i=where+1;i<=N;i++)
{
sumnow+=a[i];
hash_right[sumnow]++;
}
for(int i=0;i<=2*N;i++)
ans+=hash_left[i]*hash_right[2*N-i];
}
int main()
{
//freopen("input.in","r",stdin);
//freopen("output.out","w",stdout);
scanf("%d%d",&N,&B);
for(int i=1;i<=N;i++)
{
scanf("%d",&a[i]);
if(a[i]==B)
{
a[i]=0;
where=i;
}
else a[i]=a[i]<B?-1:1;
}
work();
printf("%d\n",ans);
//system("pause");
return 0;
}