萌新求助,权值线段树re最后10个点

P1908 逆序对

线段树壹零 @ 2019-04-27 11:09:00

#include<cstdio>
#define M 10000009
#define ll long long
using namespace std;
inline ll read()
{
    ll f=0,x=1;char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')x=-1;ch=getchar();
    }
    while(ch>='0'&&ch<='9')f=(f<<1)+(f<<3)+ch-'0',ch=getchar();
    return f*x;
} 
struct segtree
{
    int ls,rs;ll w;
}tree[4*M];
ll cnt=2,n,a,ans=0;
inline void insert(ll l,ll r,ll p,ll v)
{
    //tree[p].l=l;tree[p].r=r;
    if(l==r)
    {
        //printf(" %d %d\n",l,ans);
        tree[p].w++;return ;
    }
    ll mid=l+r>>1;
    if(!tree[p].ls)tree[p].rs=cnt++,tree[p].ls=cnt++;
    if(v<=mid)ans+=tree[tree[p].rs].w,insert(l,mid,tree[p].ls,v);
    else if(mid<v)insert(mid+1,r,tree[p].rs,v);
    tree[p].w=tree[tree[p].ls].w+tree[tree[p].rs].w;
}
int main()
{
    n=read();
    for(ll i=1;i<=n;i++)
    {
        a=read();
        insert(1,1e9,1,a);
        //printf("%d %d\n",i,ans);
    }

    printf("%lld\n",ans);
    return 0;
}

by Soulist @ 2019-04-27 11:21:56

用权值线段树貌似空间有点小紧张...


by Soulist @ 2019-04-27 11:25:13

推荐离散化一下后搞O(n)的空间。


by 线段树壹零 @ 2019-04-27 11:34:05

@Mital 十分感谢。


|