Ping pong(树状数组经典)

时间:2021-09-05 03:36:40

Ping pong

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4874    Accepted Submission(s): 1777

Problem Description
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
题解:

把运动员排成一排,对于其中任意一个位置i上的人来说,如果他作为裁判,则有这么两种可能:

1.左边的某人能力值低于他,右边高于他;

2.左边的某人能力值高于他,右边低于他。

记左边比他小的人数为l[i],右边比他小的人数为r[i],

那么左边比他大的人数为i-1-l[i],右边比他大的人数为n-i-r[i],

则i作为裁判就有l[i]*(n-i-r[i])+(i-1-l[i])*r[i];

前缀 后缀比i人大的数用树状数组求;

那么代码为:

要用long long ;

代码:

 #include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<algorithm>
//#define LOCAL
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=;
int tree[MAXN+],a[MAXN],bl[MAXN],br[MAXN];
int lowbit(int x){
return x&(-x);
}
void update(int x){
while(x<=MAXN){
tree[x]++;
x+=lowbit(x);
}
}
int SUM(int x){
int temp=;
while(x){
temp+=tree[x];
x-=lowbit(x);
}
return temp;
}
int main(){
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
int T,N;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i=;i<=N;i++)scanf("%d",a+i);
memset(tree,,sizeof(tree));
for(int i=;i<=N;i++){
bl[i]=SUM(a[i]);
update(a[i]);
}
memset(tree,,sizeof(tree));
for(int i=N;i>;i--){
br[i]=SUM(a[i]);
update(a[i]);
}
long long ans=;
for(int i=;i<=N;i++){
ans+=bl[i]*(N-i-br[i])+br[i]*(i--bl[i]);
}
printf("%lld\n",ans);
}
return ;
}