LA4329

来源:互联网 发布:求方位角的简易算法 编辑:程序博客网 时间:2024/05/19 01:11

LA4329 Ping pong(树状数组与组合原理)

N (3$ \le$N$ \le$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$ \le$T$ \le$20) <tex2html_verbatim_mark>, indicating the number of test cases, followed by T<tex2html_verbatim_mark>lines each of which describes a test case.

Every test case consists of N + 1 integers. The first integer is N <tex2html_verbatim_mark>, the number of players. Then N distinct integersa1a2...aN <tex2html_verbatim_mark>follow, indicating the skill rank of each player, in the order of west to east ( 1$ \le$ai$ \le$100000 <tex2html_verbatim_mark>, i = 1...N).

 

Output 

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

 

Sample Input 

 

13 1 2 3

 

Sample Output 

1


题目大意:
一条大街上住着n个乒乓球爱好者,经常组织比赛切磋技术。每个人都有一个能力值a[i]。每场比赛需要三个人:两名选手,一名裁判。他们有个奇怪的约定,裁判必须住在两名选手之间,而裁判的能力值也必须在两名选手之间。问一共能组织多少种比赛。

分析:
考虑第i个人,假设a1到ai-1中有ci个比ai小,那么就有(i-1)-ci个比ai大;同理,如果ai+1到an中有di个比ai小,那么就有(n-i)-di个比ai大。更具乘法原理和加法原理,i当裁判就有
ci * (n-i-di) + (i-1-ci)*di

种比赛。(感觉这种思路简直碉堡了)

代码如下

//LA 4329输转数组求比赛的场次数,裁判不一样,视为不同比赛. #include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace  std;#define maxn 101000int c[maxn],n;int lowbit(int x)//求x的低位1对应的10进制的值。 {return x&(-x);}void add(int x,int d)//树状数组的更新. {while(x<=n){c[x]+=d;x+=lowbit(x);}}int sum(int x)//树状数组的求和 {int sum1 = 0;while(x>0){sum1+=c[x];x-=lowbit(x);}return sum1;}int main(){int a[maxn],l[maxn],r[maxn];int T,i;scanf("%d",&T);while(T--){scanf("%d",&n);for(i=1;i<=n;i++){scanf("%d",&a[i]);}memset(c,0,sizeof(c));add(a[1],1);for(int i=2;i<=n;i++)//按输入顺序查找比a[i]小的元素的个数 {l[i]=sum(a[i]);add(a[i],1);}memset(c,0,sizeof(c));//注意要对c[]数组清空. add(a[n],1);for(int i=n-1;i>=1;i--)//找出大于a[i]的元素的个数,依次标记比a[i]大的值,其中n-i为区间的元素个数,sum(a[i])求出比a[i] 小的元素的个数//n-i-sum(a[i])求出比a[i]大的元素的个数. {r[i]=(n-i)-sum(a[i]);add(a[i],1);}int sum2 = 0;for(int i=1;i<=n;i++)// 求出总的比赛场次数 {sum2+=(i-1-l[i])*(n-i-r[i])+l[i]*r[i];}printf("%d\n",sum2);}return 0;}


0 0
原创粉丝点击