您的位置:首页 > 其它

POJ 3928 Ping pong(树状数组)

2014-06-27 19:52 393 查看
裸的树状数组大白书P197有详细的解释,注意每个点找过之后要更新,就行了啊。

Ping pong

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 1842 Accepted: 721
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

#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#define eps 1e-7
//#define M 1000100
//#define LL __int64
#define LL long long
#define INF 0x3f3f3f3f
#define PI 3.1415926535898

const int maxn = 100100;

using namespace std;

struct node
{
int lsum1, rsum1;
int lsum2, rsum2;
} f[maxn];

int num[maxn];
int sum[maxn];
int n;

int low_bit(int x)
{
return x&(-x);
}
void add(int x, int d)
{
while(x < maxn)
{
sum[x] += d;
x += low_bit(x);
}
}
int sum1(int x)
{
int ans = 0;
while(x > 0)
{
ans += sum[x];
x -= low_bit(x);
}
return ans;
}

int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d",&num[i]);
memset(sum, 0, sizeof(sum));
for(int i = 1; i <= n; i++)
{
int x = sum1(num[i]);
f[i].lsum1 = x;
f[i].rsum1 = i-x-1;
add(num[i], 1);
}
memset(sum, 0, sizeof(sum));
for(int i = n; i >= 1; i--)
{
int x = sum1(num[i]);
f[i].lsum2 = x;
f[i].rsum2 = n-i-x;
add(num[i], 1);
}
LL ans = 0;
for(int i = 1; i <= n; i++)
ans += (LL)(f[i].lsum1*f[i].rsum2+f[i].lsum2*f[i].rsum1);
printf("%I64d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: