LA4329树状数组

通过算竞赛入门经典训练指南了解了这题,把我一直搞不懂的树状数组终于搞懂了,感觉线段树还更容易懂一点,但是树状数组确实比线段树更好用。

N (3 ≤ N ≤ 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 ≤ T ≤ 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 a1, a2 . . . aN follow, indicating the skill rank of each player, in the order of west to east

(1 ≤ ai ≤ 100000, i = 1 . . . N).

Output

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

Sample Input

1 3 1 2 3

Sample Output

1

题目的意思是一条街上有n个乒乓球爱好者,经常比赛,比赛要三个人,且裁判必须住在他们中间且技术值夜的在他们中间,问能举办多少种比赛。

这题用树状数组很方便。

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=20005;
const int maxm=100005;
int lv[maxn],rv[maxn],T,N,C[maxm],A[maxm];
int lowbit(int x){
	return x&(-x);
}
void add(int x){
	while(x<=maxm){
		C[x]+=1;
		x+=lowbit(x);
	}
}

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

int main(){
	scanf("%d",&T);
	while(T--){
		scanf("%d",&N);
		memset(C,0,sizeof(C));
		for(int i=0;i<N;i++){
			scanf("%d",&A[i]);
			add(A[i]);
			lv[i+1]=sum(A[i]-1);
		}
		memset(C,0,sizeof(C));
		for(int i=N-1;i>=0;i--){
			add(A[i]);
			rv[i+1]=sum(A[i]-1);
		}
		LL ans=0;
		for(int i=1;i<=N;i++){
			ans+=(LL)lv[i]*(N-rv[i]-i)+(LL)rv[i]*(i-lv[i]-1);
		}
			printf("%lld\n",ans);
	}
	return 0;
}

C数组的每个元素,都是A数组中的一段连续和。C[i]=A[i-lowbit(i)]+A[i-lowbit(i)+2]+...+Ai.

lowbit(x)为x的二进制最右边的1对应的值。

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