hdu 2492(树状数组) Ping pong

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5081    Accepted Submission(s): 1871


Problem 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
 
Source
 
题意:在一条街上,每个人都有一个不同的武力值,两个人可以相互对决,但是对决必须得满足一个条件,那就是要找个裁判,
裁判的武力值只能介于两者之间,而且两个人对决地点只能在裁判家里,裁判的家必须位于两者之间。问总共有多少种对决方案?

题解:对每一个进行判断,利用树状数组正向,找出每个点左边比它小的数的数量为 x ,那么左边比它大的点的数量为 i-1-x 个
再次利用树状数组进行反向插入,找出每个点右边比它小的点的数量为 y ,那么右边比他大的点的数量为 n - i - y 个,根据乘法原
理对于每个点的答案为 x*(n-i-y)+y*(i-1-x).
 
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 100005;
int n,c[N],L[N],a[N];
int lowbit(int x){
    return x&(-x);
}
void update(int idx,int v){
    for(int i=idx;i<=N;i+=lowbit(i)){
        c[i]+=v;
    }
}
int getsum(int idx){
    int sum = 0;
    for(int i=idx;i>=1;i-=lowbit(i)){
        sum+=c[i];
    }
    return sum;
}
int main()
{
    int tcase;
    scanf("%d",&tcase);
    while(tcase--){
        scanf("%d",&n);
        long long cnt = 0;
        memset(c,0,sizeof(c));
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            update(a[i],1);
            L[i] = getsum(a[i]-1);
           // printf("%d
",L[i]);
        }
        memset(c,0,sizeof(c));
        for(int i=n;i>=1;i--){
            update(a[i],1);
            int y = getsum(a[i]-1);
           // printf("%d
",y);
            cnt+= L[i]*(n-i-y)+y*(i-L[i]-1);
        }
        printf("%lld
",cnt);
    }
    return 0;
}