离散化+树状数组 40 分求助

P1908 逆序对

wxq7889 @ 2024-02-29 21:25:53

#include <bits/stdc++.h>
constexpr int N = 500005;
int c[N], d[N], b[N];
int main()
{
    int n;
    std::cin >> n;
    std::vector<int> a(n + 1);

    for(int i = 1; i <= n; i++){
        std::cin >> a[i];
        b[i] = i;
    }
    auto cmp = [&](int i, int j){
        if(a[i] == a[j]){
                return a[i] < a[j];
              }
        return a[i] < a[j];
    };
    std::sort(b + 1, b + 1 + n, cmp);
    for(int i = 1; i <= n; i++){
        d[b[i]] = i;
    }
    auto add = [&](int x){
        while(x <= n){
            c[x] += 1;
            x += x & -x;
        }
    };
    auto sum = [&](int x){
        int res = 0;
        while(x){
            res += c[x];
            x -= x & -x;
        }
        return res;
    };
    long long ans = 0;
    for(int i = 1; i <= n; i++){
        add(d[i]);
        ans += i - sum(d[i]);
    }
    std::cout << ans <<std::endl;
    return 0;
}

by Dark_Star @ 2024-03-28 19:50:53

auto cmp = [&](int i, int j){
        if(a[i] == a[j]){
                return a[i] < a[j];
              }
        return a[i] < a[j];
    };

++魔怔次数 @wxq7889


|