LA 4329(树状数组)

题目描述:

N <tex2html_verbatim_mark>(3LA 4329(树状数组)NLA 4329(树状数组)20000) <tex2html_verbatim_mark>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 <tex2html_verbatim_mark>(1LA 4329(树状数组)TLA 4329(树状数组)20) <tex2html_verbatim_mark>, indicating the number of test cases, followed by T <tex2html_verbatim_mark>lines each of which describes a test case.

Every test case consists of N + 1 <tex2html_verbatim_mark>integers. The first integer is N <tex2html_verbatim_mark>, the number of players. Then N <tex2html_verbatim_mark>distinct integers a1a2...aN <tex2html_verbatim_mark>follow, indicating the skill rank of each player, in the order of west to east ( 1LA 4329(树状数组)aiLA 4329(树状数组)100000 <tex2html_verbatim_mark>, i = 1...N <tex2html_verbatim_mark>).

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],算出从a[1]到a[i-1]比a[i]小的数有c[i]个,a[i+1]到a[n]比a[i]小的有d[i]个,则考虑当i为裁判时,可能的方案数为:c[i](n-i-d[i])+d[i](i-c[i]-1)。关键是算c[i]、d[i]。运用树状数组可以算出c[i],d[i]。

 #include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
using namespace std;
const int maxn=;
const int maxv=;
int a[maxn],c[maxv],cc[maxn],d[maxn],n;
int lowbit(int x){
return x&-x;
}
int sum(int x){
int res=;
while(x>){
res+=c[x];
x-=lowbit(x);
}
return res;
}
void add(int x,int v){
while(x<=maxv){
c[x]+=v;
x+=lowbit(x);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
memset(c,,sizeof(c));
for(int i=;i<=n;i++)
scanf("%d",&a[i]);
for(int i=;i<=n-;i++){
cc[i]=sum(a[i]-);
add(a[i],);
}
memset(c,,sizeof(c));
for(int i=n;i>=;i--){
d[i]=sum(a[i]-);
add(a[i],);
}
ll ans=;
for(int i=;i<=n-;i++)
ans+=cc[i]*(n-i-d[i])+(i-cc[i]-)*d[i];
printf("%lld\n",ans);
}
return ;
}
上一篇:makefile中的shell语法


下一篇:JAVA语法细节(1)