1303: [CQOI2009]中位数图
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 1452 Solved: 951
[ 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
模拟。
找到b所在位置为p。
记录1-p的s[i]表示i到p之间比b大的数的个数-比b小的数的个数。
而p到n的s'[i]则与s[i]相反,并用cnt[k]来记录s'[i]=k的有几个。
那么左右可以配对需要满足的条件就是s[i]=-s'[i],那么直接从1-p扫一遍,加上对应的cnt[-s[i]]即可。
对于负数整体加上一个数,让他变成正的即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define k 100000
#define LL long long
using namespace std;
int n,b,a[k+5],cnt[k*2+5],s[k+5];
void read(int &tmp)
{
tmp=0;
char ch=getchar();
int fu=1;
for (;ch<'0'||ch>'9';ch=getchar())
if (ch=='-') fu=-1;
for (;ch>='0'&&ch<='9';ch=getchar())
tmp=tmp*10+ch-'0';
tmp*=fu;
}
int main()
{
read(n),read(b);
int p=0;
for (int i=1;i<=n;i++)
{
read(a[i]);
if (a[i]==b) p=i;
}
for (int i=p-1;i;i--)
if (a[i]>b) s[i]=s[i+1]+1;
else s[i]=s[i+1]-1;
int now=0;
cnt[k]++;
for (int i=p+1;i<=n;i++)
{
if (a[i]>b) now++;
else now--;
cnt[now+k]++;
}
LL ans=0;
for (int i=1;i<=p;i++)
ans+=cnt[k-s[i]];
printf("%lld\n",ans);
return 0;
}