zoukankan      html  css  js  c++  java
  • 51nod 1682 中位数计数(差分统计)

    中位数定义为所有值从小到大排序后排在正中间的那个数,如果值有偶数个,通常取最中间的两个数值的平均数作为中位数。

    现在有n个数,每个数都是独一无二的,求出每个数在多少个包含其的区间中是中位数。

    首先,显然有n^2logn的算法。

    考虑枚举每个数x,求满足包含其的区间中这个数是中位数的区间个数。

    考虑前缀和,记S1[i]表示前i个数里面>x的个数,S2[i]表示前i个数里面<x的个数。

    对于任意满足条件的区间[l,r],则有S2[r]-S2[l]=S1[r]-S1[l].

    转化得S2[r]-S1[r]=S2[l]-S1[l],所以只需考虑x的两端差分值的重复次数即可统计得出答案。

    复杂度O(n^2).

    # include <cstdio>
    # include <cstring>
    # include <cstdlib>
    # include <iostream>
    # include <vector>
    # include <queue>
    # include <stack>
    # include <map>
    # include <bitset>
    # include <set>
    # include <cmath>
    # include <algorithm>
    using namespace std;
    # define lowbit(x) ((x)&(-x))
    # define pi acos(-1.0)
    # define eps 1e-8
    # define MOD 1000000007
    # define INF 1000000000
    # define mem(a,b) memset(a,b,sizeof(a))
    # define FOR(i,a,n) for(int i=a; i<=n; ++i)
    # define FDR(i,a,n) for(int i=a; i>=n; --i)
    # define bug puts("H");
    # define lch p<<1,l,mid
    # define rch p<<1|1,mid+1,r
    # define mp make_pair
    # define pb push_back
    typedef pair<int,int> PII;
    typedef vector<int> VI;
    # pragma comment(linker, "/STACK:1024000000,1024000000")
    typedef long long LL;
    inline int Scan() {
        int x=0,f=1; char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-') f=-1; ch=getchar();}
        while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();}
        return x*f;
    }
    inline void Out(int a) {
        if(a<0) {putchar('-'); a=-a;}
        if(a>=10) Out(a/10);
        putchar(a%10+'0');
    }
    const int N=8005;
    //Code begin...
    
    int a[N], num[N<<1], ans[N];
    const int P=8000;
    
    int main ()
    {
        int n=Scan();
        FOR(i,1,n) a[i]=Scan();
        FOR(i,1,n) {
           mem(num,0); num[P]=1;
           int now=0;
           FOR(j,1,i-1) {
               if (a[j]<a[i]) ++now;
               else --now;
               ++num[P+now];
           }
           ans[i]=num[P+now];
           FOR(j,i+1,n) {
               if (a[j]<a[i]) ++now;
               else --now;
               ans[i]+=num[P+now];
           }
        }
        FOR(i,1,n) printf("%d ",ans[i]);
        return 0;
    }
    View Code
  • 相关阅读:
    mybatis-generator自动生成代码时,只生成insert方法
    elasticsearch-head-master下运行npm install报npm WARN elasticsearch-head@0.0.0 license should be a valid SPDX license expression
    fs.default.name和fs.defaultFS
    zookeeper集群为什么要是单数
    Quorom机制
    把数据库放入Docker是一个好主意吗?
    JVM GC算法CMS详解
    JVM之——CMS
    对于TCP/IP协议的三次握手和四次挥手的理解
    JVM G1和CMS
  • 原文地址:https://www.cnblogs.com/lishiyao/p/7195878.html
Copyright © 2011-2022 走看看