bzoj1303 [CQOI2009]中位数图

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\leqslant 100000\)

Solution

显然要求子序列中大于\(b\)的个数等于小于\(b\)的个数。用前缀和,小于\(b\)的记为\(-1\),大于\(b\)的记为\(1\)\(l[i]\)表示左边前缀和为\(i\)的位置的个数,\(r[i]\)表示右边前缀和为\(i\)的位置的个数。注意负数处理。

#include<bits/stdc++.h>
using namespace std;

inline int read() {
	int x = 0, flag = 1; char ch = getchar();
	while (ch > '9' || ch < '0') { if (ch == '-') flag = -1; ch = getchar(); }
	while (ch <= '9' && ch >= '0') { x = x * 10 + ch - '0'; ch = getchar(); }
	return x * flag;
}
inline void write(int x) { if (x >= 10) write(x / 10); putchar(x % 10 + '0'); }

#define N 100001
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define drp(i, a, b) for (int i = a; i >= b; i--)

int n, b, a[N];
int num[N];
int l[N << 1], r[N << 1];

int main() {
	cin >> n >> b;
	int pos = 0, sum, ans;
	rep(i, 1, n) {
		a[i] = read();
		if (a[i] == b) pos = i, num[i] = 0;
		else if (a[i] < b) num[i] = -1;
		else num[i] = 1;
	}
	l[n] = r[n] = 1;
	sum = 0; drp(i, pos - 1, 1) sum += num[i], l[sum + n]++;
	sum = 0; rep(i, pos + 1, n) sum += num[i], r[sum + n]++;
	ans = 0; rep(i, 0, (n << 1) - 1) ans += l[i] * r[2 * n - i];
	write(ans);
	return 0;
}
posted @ 2018-02-05 09:35  aziint  阅读(101)  评论(0编辑  收藏  举报
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.