bzoj 1303: [CQOI2009]中位数图

 题目链接

给n个数,一个值b, 统计所有以b为中位数的序列的个数。序列长度为奇数。数字在1-n之间, 每个数只出现一次。

如果一个数大于b, 那么将他赋值为1, 小于b赋值为-1, 记录数组中b出现的位置, 为pos。

具体看代码.......好难说清

#include<bits/stdc++.h>
using namespace std;const int maxn = 1e5+5;
int a[maxn], l[maxn*2], r[maxn*2];
int main()
{
    int n, b, x, pos;
    while(cin>>n>>b) {
        for(int i = 0; i<n; i++) {
            scanf("%d", &x);
            if(x == b) {
                pos = i;
            } else if(x<b) {
                a[i] = -1;
            } else {
                a[i] = 1;
            }
        }
        int sum = 0;
        l[n] = r[n] = 1;
        for(int i = pos-1; i>=0; i--) {
            sum += a[i];
            l[sum+n]++;             //因为数组不能有负数, 所以+n
        }
        sum = 0;
        for(int i = pos+1; i<n; i++) {
            sum += a[i];
            r[sum+n]++;
        }
        sum = 0;
        for(int i = 0; i<2*n; i++) {
            sum += l[i]*r[2*n-i];
        }
        cout<<sum<<endl;
    }
    return 0;
}

 

posted on 2015-12-21 17:02  yohaha  阅读(148)  评论(0编辑  收藏  举报

导航