Ping pong
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2611 Accepted Submission(s): 973
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?
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).
3 1 2 3
#include<iostream>
#include<cstdio>
#include<cstring> using namespace std; const int N=; int n,arr[N+],a[N+];
int lmin[N+],lmax[N+],rmin[N+],rmax[N+]; int lowbit(int x){
return x&(-x);
} void update(int i,int val){
while(i<=N){
arr[i]+=val;
i+=lowbit(i);
}
} int Sum(int i){
int ans=;
while(i>){
ans+=arr[i];
i-=lowbit(i);
}
return ans;
} int main(){ //freopen("input.txt","r",stdin); int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
memset(arr,,sizeof(arr));
for(int i=;i<=n;i++)
scanf("%d",&a[i]);
for(int i=;i<=n;i++){
update(a[i],);
lmin[i]=Sum(a[i]-); //求左边有多少个数比自己小
lmax[i]=Sum(N)-Sum(a[i]); //求左边有多少个数比自己大
}
memset(arr,,sizeof(arr));
for(int i=n;i>=;i--){
update(a[i],);
rmin[i]=Sum(a[i]-); //求右边有多少个数比自己小
rmax[i]=Sum(N)-Sum(a[i]); //求右边有多少个数比自己大
}
long long ans=;
for(int i=;i<=n;i++)
ans+=lmin[i]*rmax[i]+lmax[i]*rmin[i]; //1.左边比自己大的数*右边比自己小的数
//2.左边比自己小的数*右边比自己大的数 ,相加就是总和
cout<<ans<<endl;
}
return ;
}