hdu4908(中位数)

时间:2023-03-10 06:12:34
hdu4908(中位数)

传送门:BestCoder Sequence

题意:给一个序列,里面是1~N的排列,给出m,问以m为中位数的奇数长度的序列个数。

分析:先找出m的位置,再记录左边比m大的状态,记录右边比m大的状态,使得左右两边状态平衡(和为0)就是满足的序列。

举例:

7 4

1 5 4 2 6 3 7

ans=8

m的位置pos=3:0

左边:0  1

右边:-1 0 -1 0

那么左边的0可以和右边的两个0组合(<1 5 4 2 4>,<1 5 4 2 6 3 7>).

左边的1和右边的两个-1组合(<5 4 2>,<5 4 2 6 3>).

中间pos可以和左右两边为0的组合还有自己本身(<1 5 4>,<4 2 6>,<4 2 6 3 7>,<4>)

因此总共8个。

5 3

1 2 3 4 5

ans=3

3的位置pos=3:0

左边:-2 -1

右边:1 2

左边-1可以和右边1可以组合(<2 3 4>)

左边-2和可以右边-2组合(<1 2 3 4 5>).

加上自己本身,因此ans=3.

#pragma comment(linker,"/STACK:1024000000,1024000000")
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <limits.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdlib>
#include <stack>
#include <vector>
#include <set>
#include <map>
#define LL long long
#define mod 100000000
#define inf 0x3f3f3f3f
#define eps 1e-6
#define N 60010
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define PII pair<int,int>
using namespace std;
inline int read()
{
char ch=getchar();int x=,f=;
while(ch>''||ch<''){if(ch=='-')f=-;ch=getchar();}
while(ch<=''&&ch>=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
int n,m,pos;
int a[N<<],c[N<<];
int main()
{
while(scanf("%d%d",&n,&m)>)
{
for(int i=;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]==m)pos=i;
}
int res=,ans=;
memset(c,,sizeof(c));
for(int i=pos-;i>=;i--)
{
if(a[i]>m)res++;
else res--;
if(res==)ans++;
c[res+n]++;//记录某种状态数量
}
res=;
for(int i=pos+;i<=n;i++)
{
if(a[i]>m)res++;
else res--;
if(res==)ans++;
ans+=c[n-res];//加上左边记录下来的相反状态之和
}
printf("%d\n",ans);
}
}