题解 P1908 【逆序对】

· · 题解

\text{Description}

给你 n 和 n 个数 a_1 ~ a_n ,请你求出 \{a\} 中的逆序对个数。

1 \leq n \leq 5\times10^5,1 \leq a_i \leq 10^9

\text{Solution}

跑的很慢的离散化+线段树,7696ms。最大的点 793ms 。思路就是先把数组 a 排升序,离散化一下,得到一个数组 a' 。

然后建立一个数组 q ,然后每次在 q_{a'_i} 中加一。对于每个 i 查询一下 [a'_i+1,\max_{j=1}^n (a'_i +1)] 的和就可以了。可以想一下为什么是 max_{j=1}^n (a'_i +1) 而不是 max_{j=1}^n a'_i 。然后我一开始以为有 0 ,于是就给每个 a_i 都加了 1 。事实上可以不加。

存答案的那个变量记得要开 long long !

\text{Code}

#include <cstdio>
struct node{ int l,r,lc,rc,c; } tree[2100001];
int a[1000001],b[1000001],d[1000001];
int lenb=0,lend=0,len=0;
void bt(int l,int r)
{
    len++;
    tree[len].l=l;
    tree[len].r=r;
    tree[len].lc=0;
    tree[len].rc=0;
    tree[len].c=0;
    int now=len;
    if(l<r)
    {
        int mid=(l+r)/2;
        tree[len].lc=len+1;
        bt(l,mid);
        tree[now].rc=len+1;
        bt(mid+1,r);
    }
}
void change(int now,int x,int t)
{
    if(tree[now].l==tree[now].r)
    {
        tree[now].c+=t;
        return ;
    }
    int mid=(tree[now].l+tree[now].r)/2;
    if(x<=mid)
    {
        change(tree[now].lc,x,t);
    }
    else
    {
        change(tree[now].rc,x,t);
    }
    tree[now].c=tree[tree[now].lc].c+tree[tree[now].rc].c;
}
int findsum(int now,int l,int r)
{
    if(tree[now].l==l && tree[now].r==r)
    {
        return tree[now].c;
    }
    int mid=(tree[now].l+tree[now].r)/2;
    if(r<=mid)
    {
        return findsum(tree[now].lc,l,r);
    }
    else if(mid+1<=l)
    {
        return findsum(tree[now].rc,l,r);
    }
    else
    {
        return findsum(tree[now].lc,l,mid)+findsum(tree[now].rc,mid+1,r);
    }
}
void px(int l,int r)
{
    int x=l,y=r,mid=b[(l+r)/2];
    while(x<=y)
    {
        while(b[x]<mid)
        {
            x++;
        }
        while(b[y]>mid)
        {
            y--;
        }
        if(x<=y)
        {
            int t=b[x];
            b[x]=b[y];
            b[y]=t;
            x++;
            y--;
        }
    }
    if(l<y)
    {
        px(l,y);
    }
    if(x<r)
    {
        px(x,r);
    }
}
int find(int x)
{
    int l=1,r=lend;
    while(l<r)
    {
        int mid=(l+r)/2;
        if(d[mid]<x)
        {
            l=mid+1;
        }
        else
        {
            r=mid;
        }
    }
    return l;
}
int main()
{
    long long ans=0;
    int ma=0,n=0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        a[i]++;
        b[++lenb]=a[i];
    }
    px(1,lenb);
    for(int i=1;i<=lenb;i++)
    {
        if(b[i]!=b[i-1])
        {
            d[++lend]=b[i];
        }
    }
    for(int i=1;i<=n;i++)
    {
        a[i]=find(a[i]);
        if(a[i]>ma)
        {
            ma=a[i];
        }
    }
    bt(1,ma+1);
    change(1,a[1],1);
    for(int i=2;i<=n;i++)
    {
        ans+=(long long)findsum(1,a[i]+1,ma+1);
        change(1,a[i],1);
    }
    printf("%lld",ans);
    return 0;
}