CF538F A Heap of Heaps (可持久化线段树+调和级数)

题意

给出一个序列,请你依次输出在序列上建立k(1~n-1)元小根堆,会出现的不合法的元素数量。不合法的意思是这个元素大于它的父节点,不符合小根堆的性质。

题解

暴力枚举K,同时用可持久化线段树维护区间内大于指定数的元素数量,因为这个过程是一个调和级数,所以时间复杂度是合理的。

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+100;
const int M=maxn*40;
int a[maxn],t[maxn];
int n,m;
int T[maxn],lson[M],rson[M],c[M],tot;
int build (int l,int r) {
    int root=tot++;
    c[root]=0;
    if (l!=r) {
        int mid=(l+r)>>1;
        lson[root]=build(l,mid);
        rson[root]=build(mid+1,r);
    }
    return root;
}
int up (int root,int p,int v) {
    int newRoot=tot++;
    int tmp=newRoot;
    int l=1,r=m;
    while (l<r) {
        int mid=(l+r)>>1;
        if (p<=mid) {
            lson[newRoot]=tot++;
            rson[newRoot]=rson[root];
            newRoot=lson[newRoot];
            root=lson[root];
            r=mid;
        }
        else {
            rson[newRoot]=tot++;
            lson[newRoot]=lson[root];
            newRoot=rson[newRoot];
            root=rson[root];
            l=mid+1;
        }
        c[newRoot]=c[root]+v;
    }
    return tmp;
}

int query (int left_root,int right_root,int l,int r,int L,int R) {
    if (R<L) return 0;
    if (l>=L&&r<=R) return c[left_root]-c[right_root];
    int mid=(l+r)>>1;
    int ans=0;
    if (L<=mid) ans+=query(lson[left_root],lson[right_root],l,mid,L,R);
    if (R>mid) ans+=query(rson[left_root],rson[right_root],mid+1,r,L,R);
    return ans; 
}

int main () {
    scanf("%d",&n);
    for (int i=1;i<=n;i++) scanf("%d",a+i),t[i]=a[i];
    sort(t+1,t+n+1);
    m=unique(t+1,t+n+1)-t-1;
    for (int i=1;i<=n;i++) a[i]=upper_bound(t+1,t+m+1,a[i])-t-1;
    T[n+1]=build(1,m);
    for (int i=n;i;i--) T[i]=up(T[i+1],a[i],1);
    for (int k=1;k<n;k++) {
        int ans=0;
        for (int i=1;i<=n;i++) {
            if (k*(i-1)+2>n) break;
            ans+=query(T[k*(i-1)+2],T[min(n,k*i+1)+1],1,m,1,a[i]-1);
        }
        printf("%d ",ans);
    }
} 

 

posted @ 2020-11-11 14:38  zlc0405  阅读(70)  评论(0编辑  收藏  举报