BZOJ 1303: [CQOI2009]中位数图

题目大意:

给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b。中位数是指把所有元素从小到大排列后,位于中间的数。

题解:
从中位数向左右扫,小于b减一,大于b加一。让左右两边之和为0就是一个合法的连续子序列,开了个map。

代码:

#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;
int a[1000005];
map<int,int> suml,sumr;
int main(){
	int n,b;
	scanf("%d%d",&n,&b);
	int id;
	for (int i=1; i<=n; i++){
		scanf("%d",&a[i]);
		if (a[i]==b) id=i;
	}
	suml[0]=1;
	int ss=0;
	for (int i=id-1; i>=1; i--){
		if (a[i]<b) ss--;
		else ss++;
		suml[ss]++;
	}
	sumr[0]=1;
	ss=0;
	for (int i=id+1; i<=n; i++){
		if (a[i]<b) ss--;
		else ss++;
		sumr[ss]++;
	}
	long long ans=0;
	for (int i=-n; i<=n; i++)
		ans+=1ll*suml[i]*sumr[-i];
	printf("%lld\n",ans);
	return 0;
}

  

posted @ 2018-04-07 20:14  ~Silent  阅读(107)  评论(0编辑  收藏  举报
Live2D