51nod 1682 中位数技术(前缀和)

问在给出序列中每个元素在包含他的区间中作为中位数的次数
显然有n^2logn的方法,然后卡到窒息
看了别人的
就用一种类似前缀计数的方法
bg[i] 到i大于的
sm[i] 小于的
bg[r]-bg[l]=sm[r]-sm[l]
=>
bg[r]-sm[r] = bg[l]-sm[l]
注意细节即可

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
#define debug(x) //std::cerr << #x << " = " << (x) << std::endl
typedef long long LL;
const int MAXN = 8e3 + 17;
const int MOD = 1e9 + 7;
int a[MAXN],ans[MAXN],sm[MAXN],bg[MAXN],ocr[100000+10000];
int main(int argc, char const *argv[])
{
#ifdef noob
    freopen("Input.txt", "r", stdin);
    freopen("Output.txt", "w", stdout);
#endif
    int n;
    cin>>n;    
    for (int i = 0; i < n; ++i)
    {
        scanf("%d",&a[i]);
    }
    for (int i = 0; i < n; ++i)
    {
        memset(sm, 0, sizeof(sm));
        memset(bg, 0, sizeof(bg));
        memset(ocr, 0, sizeof(ocr));
        ocr[100000+0] = 1;
        for (int j = 0; j < n; ++j)
        {
            sm[j] = j==0?0:sm[j-1];
            bg[j] = j==0?0:bg[j-1];
            if(a[j]<a[i]) 
                sm[j]++;
            else if(a[j]>a[i])
                bg[j]++;
            if(i<=j&&ocr[100000+bg[j]-sm[j]])
                ans[i]+=ocr[100000+bg[j]-sm[j]];
            if(j<i)ocr[100000+bg[j]-sm[j]]++;
        }
    }
    for (int i = 0; i < n; ++i)
    {
        printf("%d ",ans[i]);
    }
    cout<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37802215/article/details/81107295