码迷,mamicode.com
首页 > 编程语言 > 详细

UVALive 4329 Ping pong (树状数组)

时间:2016-07-29 16:33:35      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

白书上的例题。花了很多时间在找bug上,刚学树状数组,这道题add操作时要注意上限不是n。

 

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll maxn = 1e5 + 10;
ll C[maxn];
ll n;

inline ll lowbit(ll x) {
    return x & (-x);
}

ll sum(ll x) {
    ll ret = 0;
    while(x > 0) {
        ret += C[x]; x -= lowbit(x);
    }
    return ret;
}

void add(ll x, ll d) {
    while(x <= maxn) {
        C[x] += d; x += lowbit(x);
    }
}

ll a[maxn];
ll r[maxn], l[maxn];

int main() {
    ll t;
    scanf("%I64d", &t);
    while(t--) {
        memset(C, 0, sizeof(C));
        scanf("%I64d", &n);
        for(ll i = 1; i <= n; i++) {
            scanf("%I64d", &a[i]);
            add(a[i], 1);
            l[i] = sum(a[i] - 1);
        }
        memset(C, 0, sizeof(C));
        for(ll i = n; i >= 1; i--) {
            add(a[i], 1);
            r[i] = sum(a[i] - 1);
        }
        ll ans = 0;
        for(ll i = 1; i <= n; i++) {
            ans += l[i] * (n - i - r[i]) + (i - l[i] - 1LL) * r[i];
        }
        cout << ans << endl;
    }
}

 

UVALive 4329 Ping pong (树状数组)

标签:

原文地址:http://www.cnblogs.com/lonewanderer/p/5718856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!