题意:
中位数定义为所有值从小到大排序后排在正中间的那个数,如果值有偶数个,通常取最中间的两个数值的平均数作为中位数。
现在有n个数,每个数都是独一无二的,求出每个数在多少个包含其的区间中是中位数。
Input
第一行一个数n(n<=8000) 第二行n个数,0<=每个数<=10^9
Output
N个数,依次表示第i个数在多少包含其的区间中是中位数。
Input示例
5 1 2 3 4 5
Output示例
1 2 3 2 1
思路:
弄清楚一点,如果x是这个区间的中位数,那说明该区间内有一半的数比x大,有一半的数比x小。
对于每个数x,我们先存下x左边的区间内大于x的数与小于x的数的差的出现次数,然后再看x右边的数,遍历到某个位置时大于x的数-小于x的数的个数的差为y,那么这半个区间只要和之前存下来的大小数差为-y的区间组合,就可以保证x是该区间的中位数,之前已经记录下x左边差为-y的各有多少个,然后右边查询即可。
代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 8005;
int a[MAXN], Hash[MAXN * 2], ans[MAXN];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= n; i++) {
int cnt = 0;
memset(Hash, 0, sizeof(Hash));
for (int j = i; j >= 1; j--) {
if (a[j] > a[i]) ++cnt;
if (a[j] < a[i]) --cnt;
//printf("%d : %d\n", i, cnt);
Hash[8000 + cnt]++;
}
cnt = 0;
for (int j = i; j <= n; j++) {
if (a[j] > a[i]) --cnt;
if (a[j] < a[i]) ++cnt;
ans[i] += Hash[8000 + cnt];
}
}
for (int i = 1; i <= n; i++)
printf("%d%c", ans[i], i == n ? '\n' : ' ');
return 0;
}