NC19913 [CQOI2009]中位数图(思维预处理)

题目描述

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

输入描述:

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

输出描述:

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

输入

7 4
5 7 2 4 3 1 6

输出

4

链接:https://ac.nowcoder.com/acm/problem/19913

solution

b是中位数的奇数长度的连续子序列,大于b和小于b的个数是一样的,把大于b的设为1,小于b的设为-1,等于b设为0,这样就变成了找区间和为0,b左边求后缀和,b右边求前缀和,0和左边或右边的0都符合,左边的0和右边的0也可以,左边的和右边的相反数也可以。
对样例来说:
5 7 2 4 3 1 6(原序列)
1 1 -1 0 -1 -1 1(大的变1,小的变-1,等于的变0)
1 0 -1 0 -1 -2 -1(左边后缀和,右边前缀和)

code

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int a[N], m[N];
int main()
{
    int n, b;
    cin >> n >> b;
    int x, j;
    for (int i = 1; i <= n; i++)
    {
        cin >> x;
        if (x < b) a[i] = -1;
        else if (x > b) a[i] = 1;
        else a[i] = 0, j = i;
    }
    int sum = 0, ans = 1;
    for (int i = j - 1; i >= 1; i--)
    {
        sum += a[i];
        m[sum + n]++;
        if (sum == 0) ans++;
    }
    sum = 0;
    for (int i = j + 1; i <= n; i++)
    {
        sum += a[i];
        ans += m[n - sum];
        if (sum == 0) ans++;
    }
    cout << ans << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44169557/article/details/107722752