BZOJ1303 [CQOI2009]中位数图

Time Limit: 1 Sec  Memory Limit: 162 MB
Submit: 3555  Solved: 2204
[Submit][Status][Discuss]

Description

给出1~n的一个排列,统计该排列有多少个长度为奇数的连续子序列的中位数是b。中位数是指把所有元素从小到大排列后,位于中间的数。

Input

第一行为两个正整数n和b ,第二行为1~n 的排列。

Output

输出一个整数,即中位数为b的连续子序列个数。

Sample Input

7 4
5 7 2 4 3 1 6

Sample Output

4

HINT

第三个样例解释:{4}, {7,2,4}, {5,7,2,4,3}和{5,7,2,4,3,1,6}
N<=100000

题解:
题中描述有误,应该是子串。
先找到b的位置k,然后从k往前扫,记录后缀比b大的数与比b小的数的数量差。再从k往后扫,记录前缀中比b大的数与比b小的数的数量差。综合考虑易得ans。
#include <bits/stdc++.h>
using namespace std;
int n,k,m;
int a[100005];
int mx[100005],mn[100005],cnt_0;
int main(){
    scanf("%d%d",&n,&m);
    for (int i = 0;i < n;++i){
        scanf("%d",a+i);
        if (a[i] == m) k = i;
    }
    int num = 0;
    int ans = 0;
    for (int i = k-1;i >= 0;--i){
        if (a[i] > m) num++;
            else num--;
        if (num == 0) cnt_0++;
        if (num > 0) mx[num]++;
        if (num < 0) mn[num*(-1)]++;
    }
    num = 0;
    ans = cnt_0;
    for (int i = k+1;i < n;++i){
        if (a[i] > m) num++;
            else num--;
        if (num == 0){
            ans++;
            ans += cnt_0;
        }
        if (num > 0) ans += mn[num];
        if (num < 0) ans += mx[-num];
    }
    printf("%d
",ans+1);
    return 0;
}
原文地址:https://www.cnblogs.com/mizersy/p/9750491.html