HDU 2492 Ping pong

转载请注明出处忆梦http://blog.csdn.net/yimeng2013/article/details/12942309


题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2492

LRJ书上例题

题意:给出1~n个选手的skill rank,如果两个选手要进行比赛,两个选手中间必须有一个裁判,这个裁判的skill rank介乎富这两个选手之间,问能举办多少个赛事
题解:对第i个人来说,设他前面a1~ai-1中pre[i]个人比第i个人的skill rank值小,那么就会有(i-1)-pre[i]个人比第i个人的skill rank值大。 同理设他后面ai+1~an中有suf[i]个人比第i个人的skill rank值小,那么就会有(n-i)-suf[i]个人比第i个人的skill rank值大. 
利用乘法原理有ans[i] = pre[i]*(n-i-suf[i]) + (i-1-pre[i])*suf[i];

#include<cstdio>
#include<cstring>

#define MAXN 100000+5
#define N 20000+5
int c[MAXN], pre[N], suf[N],a[N];
int maxx;
int lowbit(int x)
{
	return x & -x;
}

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

void add(int x, int d)
{
	while(x <= maxx)
	{
		c[x] += d;
		x += lowbit(x);
	}
}


int main ()
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		maxx = -1;
		int n;
		scanf("%d", &n);
		for(int i = 1; i <= n; i++)
		{
			scanf("%d", &a[i]);
			if(maxx < a[i])
				maxx = a[i];
		}

		memset(c, 0, sizeof(c));
		memset(pre, 0, sizeof(pre));
		for(int i = 1; i < n; i++)
		{
			add(a[i], 1);
			pre[i] = sum(a[i]-1);
		}
		memset(c, 0, sizeof(c));
		memset(suf, 0, sizeof(suf));
		for(int i = n; i > 1; i--)
		{
			add(a[i],1);
			suf[i] = sum(a[i]-1) ;
		}
		__int64 ans = 0;
		for(int i = 2; i < n; i++)
			ans += pre[i]*(n-i-suf[i]) + (i-pre[i]-1)*suf[i];
		
		printf("%I64d\n", ans);
	}
	return 0;
}


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