传送门:http://acm.hdu.edu.cn/showproblem.php?pid=5701
分析:枚举中位数找区间,随便先扫那一边。sum[j]表示当前枚举的数到第j个数形成的区间里当前数偏离中位数的程度。cnt[k]表示偏离程度为k的次数,由于k可能为负,所以需要处理一下,预先加上n。这里我们先向右扫描,记录cnt,再向左,当a[j]>a[i],则加1,否则减1。向左扫的时候,ans加上之前相同偏离程度的次数。
代码:
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <set>
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
const int maxn = 10000+5;
int sum[maxn], a[maxn], cnt[2*maxn];
int main(){
int n;
while(~scanf("%d", &n)){
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for(int i = 1; i <= n; i++) {
memset(cnt, 0, sizeof(cnt));
sum[i] = 0;
int ans = 1;
cnt[n]++;
for(int j = i+1; j <= n; j++) {
sum[j] = sum[j-1]+(a[j] > a[i] ? 1 : -1);
cnt[sum[j]+n]++;
if(sum[j] == 0) ans++;
}
for(int j = i-1; j >= 1; j--) {
sum[j] = sum[j+1]+(a[j] > a[i] ? 1 : -1);
ans += cnt[-sum[j]+n];
}
printf("%d%c", ans, i == n ? '\n' : ' ');
}
}
return 0;
}