傳送門: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;
}