1. 程式人生 > >LA 4329 樹狀陣列

LA 4329 樹狀陣列

N (3$ \le$N$ \le$20000) ping pong players live along a west-east street(consider the street as a line segment). Each player has a unique skill rank. To improve their skill rank, they often compete with each other. If two players want to compete, they must choose a referee among other ping pong players and hold the game in the referee's house. For some reason, the contestants can't choose a referee whose skill rank is higher or lower than both of theirs. The contestants have to walk to the referee's house, and because they are lazy, they want to make their total walking distance no more than the distance between their houses. Of course all players live in different houses and the position of their houses are all different. If the referee or any of the two contestants is different, we call two games different. Now is the problem: how many different games can be held in this ping pong street?

Input 

The first line of the input contains an integer T (1$ \le$T$ \le$20) , indicating the number of test cases, followed by T lines each of which describes a test case.

Every test case consists of N + 1 integers. The first integer is N , the number of players. Then N distinct integers a1a2...aN follow, indicating the skill rank of each player, in the order of west to east ( 1$ \le$

ai$ \le$100000 , i = 1...N ).

For each test case, output a single line contains an integer, the total number of different games.

1
3 1 2 3
1
題意:每場比賽需要3個人,裁判必須住在兩個選手之間,技能值也在兩個選手之間,求一共能組織多少種比賽
思路:考慮第I人當裁判的情形,種數有前i-1中比他小的*後(n-i)中比他大的和前i-1中比他大的*後(n-i)中比他小的。
      問題轉化為動態地修改單個元素值求字首和!這正是bit的標準用法!
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn 100080
#define LL long long int
int c[maxn],key[maxn],leftsmall[maxn],rightsmall[maxn];
int lowbit(int x)
{
	return x & (-x);
}

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

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

int main()
{
	//freopen("in.txt","r",stdin);
	int t;	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		memset(c,0,sizeof(c));
		memset(leftsmall,0,sizeof(leftsmall));
		memset(rightsmall,0,sizeof(rightsmall));
		for(int i = 1;i <= n;i++)
		{
			scanf("%d",&key[i]);
			leftsmall[i] = sum(key[i] - 1);
			update(key[i],1);
		}
		memset(c,0,sizeof(c));
		for(int i = n;i >= 1;i--)
		{
			rightsmall[i] = sum(key[i]-1);
			update(key[i],1);
		}
		LL ans = 0;
		for(int i = 1;i <= n;i++)
		{
			ans += (LL)(leftsmall[i] * (n - i - rightsmall[i])) + (LL)(rightsmall[i] * (i - 1 - leftsmall[i]));
		}
		cout << ans << endl;
		//printf("%d\n",ans);
	}
	return 0;
}