您的位置:首页 > 其它

POJ 3928 Ping pong

2016-09-17 23:34 309 查看
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

[题目大意]:

是要组成许多比赛,比赛的要求是,两个人比赛一个人作裁判,裁判的能力值必须要在两个人之间,位置也是,问一共有多少种不同的比赛方式。每个人的能力值各不相同。

[分析]:

枚举一个中间点,查找它左边有几个比它能力值小的右边有几个比它能力值大的,根据乘法原理将其相乘;再查找它左边有几个比它能力值大的右边有几个比它能力值小的,根据乘法原理将其相乘。把每个点相加就是最终结果。剩下的问题就是如何求左右需要的值。先将其从小到大进行排序,然后按原来顺序枚举中间点,计算完后就将其插入它在排序后的位置上。所以统计时就是利用树状数组统计从1到枚举的中间点在排序后的位置之间有多少数,就是左边比它小的,用此时树状数组中的所有值(就是前i个数)的减去左边它小得和就是左边比它大的,再n到1来一遍就求出右边,再相乘。

注意:要用long long。

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=20005;
int t,n;
long long ans,lmn,lmx,rmn,rmx,c[maxn];
struct node
{
int rk,id;
}a[maxn];
bool cmp(node c,node d)
{
return c.rk<d.rk;
}
int lowbit(int x)
{
return x&(-x);
}
void add(int pos)
{
while(pos<=n)
{
c[pos]++;
pos+=lowbit(pos);
}
}
long long getsum(int pos)
{
long long sum=0;
while(pos>0)
{
sum+=c[pos];
pos-=lowbit(pos);
}
return sum;
}
int main()
{
scanf("%d",&t);
while(t--)
{
ans=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].rk);
a[i].id=i;
}
memset(c,0,sizeof(c));
sort(a+1,a+n+1,cmp);
add(a[1].id);
for(int i=2;i<=n-1;i++)
{
lmn=getsum(a[i].id-1);
lmx=a[i].id-1-lmn;
rmn=getsum(n)-getsum(a[i].id);
rmx=n-rmn-a[i].id;
ans+=lmn*rmx+lmx*rmn;
add(a[i].id);
}
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: