链接:[CQOI2009]中位数图 (nowcoder.com)
题目描述:
解题思路:
因为选的连续的序列
且只取中位数
所以所有除 要选定的数 以外的数
都可以把它划分成-1和1表示它在数的左边和右边
方便后续计算
然后就通过先遍历序列种 选定数 的左边
把左边和为0的相加(和为0代表 选定数 能作为中位数)
同时记录下遍历左边时每一个连续区间的权值
然后进行右遍历
右遍历也是对权值和进行操作
不同的是在遍历的时候,顺便考虑 接 上左边区间的情况
也是权值和来相加上区间值
然后就可以实现找到所有的
中位数序列
代码详解:
#include <iostream>
using namespace std;
const int N = 1e5 + 6;
int n, b, a[N], num[N << 1];
int main() {
cin >> n >> b;
int pos = 0;
int sum = 0;
int ans = 1;
for (int i = 1; i <= n; i++) {//对数值进行操作
cin >> a[i];
if (a[i] > b) a[i] = 1;
else if (a[i] < b) a[i] = -1;
else pos = i;
}
for (int i = pos - 1; i >= 1; i--) {//操作中位数的左边
sum += a[i];
num[n + sum]++;
if (!sum) ans++;
}
sum = 0;
for (int i = pos + 1; i <= n; i++) {//操作中位数的右边
sum += a[i];
ans += num[n - sum];//左边连续区间接上右边连续区间
if (!sum) ans++;
}
cout << ans << endl;
return 0;
}