hdu 2492

树状数组

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
const int maxn1=100000;
const int maxn2=20010;
int c[maxn1+10],v[maxn2],l[maxn2],r[maxn2];
int n;
int lowbit(int x)
{
	return x&(-x);
}
void add(int x)
{
	while(x<=maxn1)//要细心
	{
		c[x]+=1;
		x+=lowbit(x);
	}
}
int sum(int x)
{
	int tot=0;
	while(x>0)
	{
		tot+=c[x];
		x-=lowbit(x);
	}
	return tot;
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		scanf("%d",&n);
		int i,a;
		for(i=1;i<=n;i++) scanf("%d",&v[i]);
		memset(c,0,sizeof(c));
		for(i=1;i<=n;i++)
		{
			add(v[i]);
			l[i]=sum(v[i]-1);
		}
		memset(c,0,sizeof(c));
		for(i=n;i>0;i--)
		{
			add(v[i]);
			r[i]=sum(v[i]-1);
		}
		long long tot=0;
		for(i=1;i<=n;i++)
		{
			tot+=l[i]*(n-i-r[i])+(i-1-l[i])*r[i];
		}
		printf("%I64d\n",tot);
	}
	return 0;
}


posted @ 2013-01-01 18:53  LJ_COME!!!!!  阅读(139)  评论(0编辑  收藏  举报