楼兰图腾 Page205 树状数组求逆序对

楼兰图腾 Page205 树状数组求逆序对

1.树状数组写起来感觉比归并好理解多了
2.求^和v的形状,求出任意一个后,可以采用将数组“倒过来”的方法,即将数组的大小关系重置一下
3.不仅是逆序对,正序对也很好求,改变遍历方向即可

代码:

/**
 *  Author1: low-equipped w_udixixi
 *  Author2: Sher丶lock
 *  Date :2020-07-03
**
Zz:overint or overarray
Xx:overwatch to 5e8
Ss:unordered map
Ww:memset or f_o_r
Ii:vector or neighbours
**
**/
#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long
#define ull unsigned long long
#define pb push_back
#define rep(x,a,b) for (int x=a;x<=b;x++)
#define repp(x,a,b) for (int x=a;x
#define W(x) printf("%d\n",x)
#define WW(x) printf("%lld\n",x)
#define pi 3.14159265358979323846
#define mem(a,x) memset(a,x,sizeof a)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int maxn=2e6+7;
const int INF=1e9;
const ll INFF=1e18;
int a[maxn],c[maxn],Lsmall[maxn],Rsmall[maxn],n;
void add(int x,int y){for (;x<=n;x+=x&-x)c[x]+=y;}
int ask(int x){int ans=0;for (;x;x-=x&-x)ans+=c[x];return ans;}
ll solve()
{
    ll cnt=0;mem(c,0);
    for (int i=n;i;i--)
    {
        Rsmall[i]=ask(a[i]-1);
        add(a[i],1);
    }
    mem(c,0);
    rep(i,1,n)
    {
        Lsmall[i]=ask(a[i]-1);
        add(a[i],1);
        cnt+=1ll*Lsmall[i]*Rsmall[i];
    }
    return cnt;
}
int main()
{
    ll ans1=0,ans2=0;
    scanf("%d",&n);
    rep(i,1,n)scanf("%d",&a[i]);
    ans1=solve();
    rep(i,1,n)a[i]=n+1-a[i];
    ans2=solve();
    printf("%lld %lld\n",ans2,ans1);
    return 0;
}

你可能感兴趣的:(《算法竞赛进阶指南》)