N (3N
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(1T
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 isN, 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 (1ai
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
区间信息维护类型的题。本题关键在于计算第i个人左右比其能力小人数,则其这个人做裁判的情况有 r_L * ( n - i - r_r) + (i - r_L) *r_ r种,r_r,r_L分别代表i左右比i能力小的人的个数;
用一个数组L记录当前能力为i的人数,初始化L 为0,能力为ai的人出现,则L[ai] ++,从左到右扫描L[ 1- ai] 则当前L中的非0的都是第i个人左边的人的能力值,统计L[1- ai]非0 的数之和即左边比第i个人能力小的人个数。本题如果从左往右依次计算,复杂度为O(n^2)。
为降低计算r_L[i]的复杂度,用一个二叉索引树维护区间性的数值情况,即 数组L[i]表示 1 - i 的所有已经出现的整数的总次数。
二进制数的十进制值为 所有1位的二进制的和,如:100110 = 100000 + 100 + 10;则 r_r[100110] = L[100000] + L[100] + L[10];只需要维护各个2^i区间的值即可,每次第L[i]++ 使得 比i 大的区段的值都加1即可!
每次++操作为O(logn), 求r_r为O(logn),则总的时间复杂度为O(nlogn);
#include <iostream>
#include <stdio.h>
#include <memory.h>
using namespace std;
const int MAX = 100000 + 10;
int a[MAX],l[MAX],r[MAX],r_l[MAX],r_r[MAX];
int t,n;
int lowbit(int i)
{
return i & -i;
}
void add(int *t,int x, int val)
{
while(x <= MAX)
{
t[x] += val; x += lowbit(x);
}
}
int sum(int *t, int x)
{
int ret = 0;
while(x)
{
ret += t[x];
x -= lowbit(x);
}
return ret;
}
void caculate()
{
memset(l,0,sizeof(l));memset(r,0,sizeof(r));
memset(r_l,0,sizeof(r_l));memset(r_r,0,sizeof(r_r));
for(int i = 0; i < n; i++)
{
add(l,a[i],1);
add(r,a[n - i - 1],1);
r_l[i] = sum(l,a[i] - 1);
r_r[n - i - 1] = sum(r,a[n - i -1] - 1);
}
//for(int i = 0; i < n; i ++)cout << a[i]<<"l=>"<<r_l[i]<<" r==>"<<r_r[i]<<endl;
long rst = 0;
for(int i = 1; i < n - 1; i++)rst += (r_l[i] * (n - 1 - i - r_r[i]) + (i - r_l[i]) * r_r[i]);
printf("%ld\n",rst);
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i = 0; i < n; i++)scanf("%d",a+i);
caculate();
}
//cout << "Hello world!" << endl;
return 0;
}