Ping pong
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 12 Accepted Submission(s) : 3
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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
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
Sample Input
1 3 1 2 3
Sample Output
1
Source
//以他们的值作为他们的下标,选取一个裁判,则他做裁判的次数等于左边等级小于他的人数乘以右边
//大于他的人数,再加上左边大于他的人数乘以右边小于他的人数。
#include<iostream>
using namespace std;
#define maxn 20005
#define maxm 100005
int tree[maxm+1];
int r[maxn+1],l[maxn+1],p[maxn+1];
int lowbit(int x){
return x&(-x);
}
void updata(int x,int c){
for(int i=x;i<=maxm;i+=lowbit(i))
tree[i]+=c;
}
int getsum(int x){
int s=0;
for(int i=x;i>=1;i-=lowbit(i))
s+=tree[i];
return s;
}
int main(){
int t,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&p[i]);
memset(tree,0,sizeof(tree)); //初始化
for(int i=1;i<=n;i++){
l[i]=getsum(p[i]-1); //统计左边等级比他小的人数
updata(p[i],1);
}
memset(tree,0,sizeof(tree));
for(int i=n;i>=1;i--){
r[i]=getsum(p[i]-1); //统计右边等级比他小的人数
updata(p[i],1);
}
__int64 sum=0;
for(int i=1;i<=n;i++)
sum+=l[i]*(n-i-r[i])+r[i]*(i-1-l[i]);//注意这一步
printf("%I64d\n",sum);
}
//system("pause");
return 0;
}