uva 1428 - Ping pong(树状数组)

integers a1, a2...aN follow, indicating the skill rank of each player, in the order of west to east ( 1$ \le$ai$ \le$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 <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int INF = 1000000000;
const int maxn = 100000 + 5;
typedef long long LL;

int a[maxn],c[maxn];
LL S_left[maxn],B_left[maxn];
int n;

int lowbit(int x){return x&-x;}

LL sum(int x){
    LL ret = 0;
    while(x > 0){
        ret += c[x];
        x -= lowbit(x);
    }
    return ret;
}

void add(int x){
    while(x <= maxn){
        c[x] += 1;
        x += lowbit(x);
    }
}

int main(){
    int t,Max;
    scanf("%d",&t);
    while(t--){
        Max = -1; 
        memset(c,0,sizeof(c));
        scanf("%d",&n);
        for(int i = 1;i <= n;i++){
            scanf("%d",&a[i]);
            add(a[i]);
            Max = max(Max,a[i]);
            S_left[i] = sum(a[i]-1);
            B_left[i] = max((LL)0,sum(Max)-sum(a[i]));
        }
        LL ans = 0;
        for(int i = 1;i <= n;i++){
            if(i == 1 || i == n) continue;
            ans += S_left[i] * ((sum(Max)-sum(a[i]))-B_left[i]);
            ans += B_left[i] * (sum(a[i]-1)-S_left[i]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值