BZOJ 1303: [CQOI2009]中位数图(前缀/后缀和乱搞)
1303: [CQOI2009]中位数图
Time Limit: 1 Sec Memory Limit: 162 MB Submit: 2480 Solved: 1529 [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
Sample Output
4
HINT
第三个样例解释:{4}, {7,2,4}, {5,7,2,4,3}和{5,7,2,4,3,1,6} N<=100000
思路:这道题的思路还是比较经典的...把大于b的数看成1,小于b的数看成-1..于是一段以b为中位数的连续的长度为奇数的数列的和为0.
那么从b往前做一个后缀和,往后做一个前缀和...然后统计每个前缀和/后缀和的值的个数..
然后枚举前缀和/后缀和可能的值(-n..n,由于负数不好处理,整体+n,变成0..2n)
具体见代码
/* ***********************************************
Author :111qqz
Created Time :2017年01月30日 星期一 20时13分11秒
File Name :code/bzoj/1303.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E5+7;
7int a[N];
8int sum[N];
9int l[N*2],r[N*2];
10int n,b;
11int pos;
12int main()
13{
14 #ifndef ONLINE_JUDGE
15 freopen("code/in.txt","r",stdin);
16 #endif
17 scanf("%d%d",&n,&b);
18 for ( int i = 1 ; i <= n ; i++)
19 {
20 scanf("%d",&a[i]);
21 if (a[i]==b) a[i] = 0,pos = i;
22 if (a[i]<b) a[i] = -1;
23 if (a[i]>b) a[i] = 1;
24 }
25 l[n]=r[n]=1;//b所在的位置
26 int ans = 0;
27 for ( int i = pos-1 ; i >=1 ; i--) {sum[i]=sum[i+1]+a[i];l[sum[i]+n]++;}
28 for ( int i = pos+1 ; i <=n ; i++) {sum[i]=sum[i-1]+a[i];r[sum[i]+n]++;}
29 for ( int i = 0 ; i <= 2*n ; i++) ans +=l[i]*r[-i+2*n];
30 cout<<ans<<endl;
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}