LA 4329(樹狀陣列)
N (3N20000) 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 (1T20) , 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
For each test case, output a single line contains an integer, the total number of different games.
1 3 1 2 3
1
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define _max 100005 int bit[_max], a[20005],Left[20005], Right[20005]; int lowbit(int x){ return (x&-x); } void add(int x, int d){ while(x<=_max){ bit[x] += d; x += lowbit(x); } } int sum(int x){ int ret = 0; while(x>0){ ret+=bit[x]; x -= lowbit(x); } return ret; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; for(int i = 0; i < n; i++){ scanf("%d", a+i); } memset(bit, 0, sizeof(bit)); add(a[0], 1); for(int i = 1; i < n-1; i++){ Left[i] = sum(a[i]); //左邊比a[i]小的個數 add(a[i], 1); } memset(bit, 0, sizeof(bit)); add(a[n-1], 1); for(int i = n-2; i>0; i--){ Right[i] =sum(a[i]); //右邊比a[i]小的個數 add(a[i], 1); } long long ans = 0; for(int i = 1; i < n-1; i++){ ans += Left[i]*(n-1-i-Right[i]) + Right[i]*(i-Left[i]); } cout<<ans<<endl; } return 0; }