1. 程式人生 > >樓蘭圖騰[樹狀陣列]

樓蘭圖騰[樹狀陣列]

傳送門

權值樹狀陣列維護一下左邊右邊比當前大或小的個數,乘起來就可以了


#include<cstdio>
#include<cstring>
#define N 200050
#define LL long long
using namespace std;
int c[N],a[N],n,l[N],r[N]; LL ans;
void Up(int x,int val){for(;x<=n;x+=x&-x)c[x]+=val;}
int Q(int x){int ans=0;for(;x;x-=x&-x)ans+=c[x];return ans;}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	for(int i=1;i<=n;i++){
		Up(a[i],1); l[i]=Q(n)-Q(a[i]);
	}
	memset(c,0,sizeof(c));
	for(int i=n;i>=1;i--){
		Up(a[i],1); r[i]=Q(n)-Q(a[i]);
	}
	for(int i=1;i<=n;i++) ans += (LL)l[i]*r[i];
	printf("%lld ",ans); ans=0;
	memset(c,0,sizeof(c));
	for(int i=1;i<=n;i++){
		l[i]=Q(a[i]); Up(a[i],1);
	}
	memset(c,0,sizeof(c));
	for(int i=n;i>=1;i--){
		r[i]=Q(a[i]); Up(a[i],1);
	}
	for(int i=1;i<=n;i++) ans += (LL)l[i]*r[i];
	printf("%lld",ans); return 0; 
}