hoj 2275 Number Sequence

知道两点即可:

一:计算出每个Ai,之前以及之后比他小的个数做乘法运算,然后求和,即是最后结果

二:找出Ai之前比Ai小的数,可以用树状数组,同理求之后的数也一样;

#include 
#include 
#include 
#define MAXN 50010

using namespace std;

int N;
int c[MAXN], a[MAXN], b[MAXN], d[MAXN];

int lowbit( int x )
{
	return x&(-x);
}

void UFset(int i, int data)
{
	while(i <= 32768)
	{
		c[i] += data;
		i += lowbit(i);
	}
}

int Querry( int x )
{
	int sum = 0;
	while(x > 0)
	{
		sum += c[x];
		x -= lowbit(x);
	}
	return sum;
}

int main()
{
	int i;
	long long ans;
	while(scanf("%d", &N) != EOF)
	{
		memset(a, 0, sizeof(a));
		memset(b, 0, sizeof(b));
		
		memset(c, 0, sizeof(c));
		for(i = 0; i < N; ++i)
		{
			scanf("%d", &d[i]);
			a[i] += Querry( d[i] );//在输入的时候就计算i之前的值比它小的值有多少个
			UFset( d[i] + 1, 1 );//然后再更新
		}

		memset(c, 0, sizeof(c));
		for(i = N-1; i >= 0; --i)
		{
			b[i] = Querry(d[i]);
			UFset(d[i] + 1, 1);
		}
		ans = 0;
		for(i = 0; i < N; ++i)
			ans += (long long)a[i] * (long long)b[i];
		printf("%lld\n", ans);
	}
	return 0;
}


 

你可能感兴趣的:(树状数组)