一道树状数组的题,hdu2492,这里就直接把题目的意思解释了吧,就是枚举每个数前后比他大的,和比他小的数的和,之后对其处理一下就可以啦,显然用树状数组进行区间更新NlogN,
在此附上题目供大家参考:
Ping pong
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3160 Accepted Submission(s): 1177
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
Source
2008 Asia Regional Beijing
直接附上AC代码:
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
int a[20005];
int x1[100010];
int x2[100010];
int y1[100010];
int y2[100010];
int c[100010];
int n;
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int value)
{
while(x <= 100010)
{
c[x] += value;
x += lowbit(x);
}
}
int sum(int x)
{
int ans = 0;
while(x > 0)
{
ans += c[x];
x -= lowbit(x);
}
return ans;
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--)
{
long long sum1 = 0;
int n;
scanf("%d",&n);
memset(c,0,sizeof(c));
for(int i = 1;i <= n;i++)
{
scanf("%d",&a[i]);
}
for(int i = 1;i <= n;i++)
{
int k = sum(a[i]);//类似求逆序数原理,在更新的过程中,把先出现的数字标记上加1.
x1[i] = k;//相当于求a[i]左侧比a[i]小的数。
x2[i] = i - k - 1;//相当于求a[i]左侧比a[i]大的数。
update(a[i],1);
}
memset(c,0,sizeof(c));
int j = 1;
for(int i = n;i >= 1;i--,j++)
{
int k = sum(a[i]);//如果找右侧的话就逆序更新树状数组来达到目的,j为更新的数字个数。
y1[i] = k;//相当于a[i]右侧比a[i]小的数。
y2[i] = j - 1 - k;//相当于a[i]右侧比a[i]大的数。
update(a[i],1);
}
for(int i = 1;i <= n;i++)
{
sum1 += (x1[i]*y2[i]+x2[i]*y1[i]);
}
cout << sum1 << endl;
}
}