HDU

来源:互联网 发布:m328晶体管测试仪编程 编辑:程序博客网 时间:2024/06/05 07:54

Ping pong

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

思路:题意要求三个人的能力值必须是单调递增或者递减的,中间的人当裁判,那么只需要统计每个人当裁判的情况。因为顺序固定,所以可以这么想:当第一遍从正序依次放入a[i],l1存储其左边比它小的数,r1存储其左边比它大的数。第二遍倒序依次放入a[i],l2存储其右边比它小的数,r2存储其右边比它大的数。最后只要把两边统计的比它大以及比它小的相乘则可以得到a[i]作为裁判的所有情况。两次遍历中间别忘了清空数组c。

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 1e5 + 10;int c[maxn], a[maxn], r1[maxn], r2[maxn], l1[maxn], l2[maxn];int lowbit(int x){    return x&(-x);}void update(int x, int y){    for(; x <= maxn; x += lowbit(x))        c[x] += y;}int getsum(int x){    int sum = 0;    for(; x > 0; x -= lowbit(x))        sum += c[x];    return sum;}int main(){    int t, n;    scanf("%d", &t);    while(t--)    {        scanf("%d", &n);        for(int i = 1; i <= n; i++)        {            scanf("%d", &a[i]);        }        long long ans = 0, cnt1 = 0, cnt2 = 0;        memset(c, 0, sizeof(c));        for(int i = 1; i <= n; i++)        {            update(a[i], 1);            r1[i] = i - getsum(a[i]);            l1[i] = getsum(a[i]) - 1;            //cout << r1[i] << " " << l1[i] << endl;        }        memset(c, 0, sizeof(c));        for(int i = n; i >= 1; i--)        {            update(a[i], 1);            r2[i] = n - i + 1 - getsum(a[i]);            l2[i] = getsum(a[i]) - 1;            //cout << r2[i] << " " << l2[i] << endl;        }        for(int i = 1; i <= n; i++)            ans = ans + l1[i]*r2[i] + l2[i]*r1[i];        printf("%lld\n", ans);    }    return 0;}