C - Ping pong hdu2492

问题描述

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?

输入

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).

输出

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

样例输入

1 
3 1 2 3

样例输出

1


这个题类似 求杭电1394求逆序数,

用树状数组来做,一个一个的扫,扫了一个就在对应的c数组位置上+1;假设第i个是裁判,则,最后  ki=(找到左边比他小的个数 乘以 右边比他大的数 )+(左边比他大的个数 乘以   右边比他小的个数),对ki求和;


#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;

const int maxx=100000+100;
int a[maxx];int c[maxx];
int s[maxx];int l[maxx];//表示左边比他小的个数和比他大的个数

int lowbit(int temp)
{
    return temp&(-temp);
}

void add(int x)
{
    while(x<=100000)
    {
        c[x]++;x+=lowbit(x);
    }
}

int sum(int x)
{
    int t=0;
    while(x>0)
    {
        t+=c[x];x-=lowbit(x);
    }
    return t;
}

int main()
{
    int k;
    scanf("%d",&k);
    while(k--)
    {
        memset(c,0,sizeof(c));
        //输入;
        int n;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        //找比他小的数;
        for(int i=1;i<=n;i++)
        {
            add(a[i]);
            s[i]=sum(a[i]-1);
        }

        //找比他大的数
        memset(c,0,sizeof(c));
        for(int i=n;i>=1;i--)
        {
            add(a[i]);
            l[i]=sum(a[i]-1);
        }

        long long summ=0;
        for(int i=1;i<=n;i++)
        {
            long long k1=s[i]*(n-i-l[i]);
            long long k2=l[i]*(i-1-s[i]);
            summ+=k1+k2;
         
        }
        cout<<summ<<endl;

    }
}


你可能感兴趣的:(C - Ping pong hdu2492)