UVALive 4329 Ping pong (树状数组)
白书上的例题。花了很多时间在找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; } }