Ping pong UVALive - 4329

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
using namespace std;

const int maxn = 20000 + 3;
int a[maxn], c[maxn], d[maxn];
int n;

struct Fenwick{
    int n;
    vector<int>A;

    void resize(int n){
        this->n = n;
        A.resize(n + 1);
    }
    void clear(){
        fill(A.begin(), A.end(), 0);
    }
    int lowbit(int v){
        return v & -v;
    }
    int sum(int x){
        int ret = 0;
        while(x > 0){
            ret += A[x];
            x -= lowbit(x);
        }
        return ret;
    }
    void add(int x, int d){
        while(x <= n){
            A[x] += d;
            x += lowbit(x);
        }
    }
};


Fenwick f;

int main()
{
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    int T;
    cin >> T;
    while(T--){
        cin >> n;
        int maxa = 0;
        for(int i = 0; i < n; i++){
            cin >> a[i];
            maxa = max(maxa, a[i]);
        }

        f.resize(maxa);
        f.clear();
        for(int i = 0; i < n; i++){
            f.add(a[i], 1);
            c[i] = f.sum(a[i] - 1);
        }
        f.clear();
        for(int i = n -1; i >= 0; i--){
            f.add(a[i], 1);
            d[i] = f.sum(a[i] - 1);
        }
        long long sum = 0;
        for(int i = 0; i < n; i++){ 
            sum += (long long)c[i]*(n-i-1-d[i]) + (long long)(i-c[i])*d[i];
        }
        cout << sum << endl;
    }
    return 0;
}
View Code

很是奇怪,为什么参考代码的resize的大小是n,它要访问到n,不应该是resize(n + 1)吗?

猜你喜欢

转载自www.cnblogs.com/sanshi-2018/p/10562766.html