4329 - Ping pong uvalive+树状数组

来源:互联网 发布:自动阅读软件 编辑:程序博客网 时间:2024/06/06 18:59

Ping pong uvalive

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) , 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 a1a2...aN follow, indicating the skill rank of each player, in the order of west to east ( 1$ \le$ai$ \le$100000 , 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
解决方案:可用数状数组来解决,求出每个位置i的左边比比他小的个数l[i],右边比他小的个数r[i],再有乘法原理和加法原理可得,i当裁判有(N-i-r[i])*l[i]+(i-l[i]-1)*r[i]个比赛,最后把每个位置能有的比赛加起来就可以了。
代码:
#include<iostream>#include<cstdio>#include<cstring>#define MMAX 120000using namespace std;long long lowbit[MMAX];long long C[MMAX];long long A[MMAX];long long l[MMAX];long long r[MMAX];long long N;void init(){    for(long long i=0;i<MMAX;i++){        lowbit[i]=i&(-1*i);    }}初始化lowbitlong long sum(long long x){ long long ret=0; while(x>0){  ret+=C[x],x-=lowbit[x]; } return ret;}///树状数组求前缀void add(long long x,long long d){while(x<=MMAX){    C[x]+=d,x+=lowbit[x];}}///树状数组更新int main(){   long long t;   scanf("%lld",&t);   init();   while(t--){    scanf("%lld",&N);    for(long long i=1;i<=N;i++){        scanf("%lld",&A[i]);    }    memset(C,0,sizeof(C));    add(A[1],1);    for(long long i=2;i<=N;i++){       l[i]=sum(A[i]);       add(A[i],1);    }    memset(C,0,sizeof(C));    add(A[N],1);    for(long long i=N-1;i>=1;i--){        r[i]=sum(A[i]);        add(A[i],1);    }    long long sum=0;    for(long long i=1;i<=N;i++){        sum+=(N-i-r[i])*l[i]+(i-l[i]-1)*r[i];    }    printf("%lld\n",sum);   }    return 0;}

0 0
原创粉丝点击