蒟蒻求助 树状数组35分

P1908 逆序对

_Nancy_ @ 2021-08-15 21:19:40

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<string>
#include<stack>
#include<queue>
#include<set>
using namespace std;
#define MAXN 500010
#define R(x) x=read()
#define W(x) write(x)
inline int read()
{
    int x,y;
    char c=getchar();
    x=0,y=1;
    while(c<'0'||c>'9') {if(c=='-') y=-1;c=getchar();}
    while(c>='0'&&c<='9') {x=(x<<3)+(x<<1)+(c^'0');c=getchar();}
    return x*y;
}
inline void write(int x)
{
    if(x<0) {putchar('-');x=-x;}
    if(x>9) write(x/10);
    putchar(x%10+'0');
}
struct node
{
    int value;
    int judge;
}a[MAXN];
int b[MAXN]
int lowbit(int);
void updata(int,int);
int getsum(int);
int c[MAXN]={0};
int n;
bool cmp(node a,node b)
{
    return a.judge>b.judge;
}
int main()
{
    R(n);
    for(int i=1;i<=n;i++) {R(a[i].judge);a[i].value=i;} 
    sort(a+1,a+1+n,cmp);
    long long sum=0;
    for(int i=1;i<=n;i++)
    {
        updata(a[i].value,1);
        sum+=getsum(a[i].value-1);
    }
    cout<<sum;
    return 0;
}
int lowbit(int x)
{
    return x&(-x);
}
void updata(int i,int v)
{
    while(i<=n)
    {
        c[i]+=v;
        i+=lowbit(i);
    }
}
long long getsum(int i)
{
    long long sum=0;
    while(i>0)
    {
        sum+=c[i];
        i-=lowbit(i);
    }
    return sum;
}

by ZkjTCTC @ 2021-08-15 22:53:32

您离站化还不如用分治法呢。

原因:因为您离站化已经要排序了,在用树状数组效率不到。注意:n<=500000!您直接先一遍排序……


by ZkjTCTC @ 2021-08-15 22:57:02

所以建议用分治。

而且树状数组求逆序队考场上不常用。


by _Nancy_ @ 2021-08-16 14:32:32

OK 我分治A了


|