35 树状数组,但是有重复数

P1908 逆序对

RedWen_shuo @ 2024-07-10 19:53:48

#include<bits/stdc++.h>
#define ll long long
#define Lowbit(x) (x & (-x))

using namespace std;

const int N = 5e6 + 1000;

struct re{
    ll x, y;
}a[N];

ll n, ansz;
ll t[N];

bool cmp(re a, re b){
    return a.x > b.x;
}

inline void add(ll pos, ll w){
    for (ll i = pos; i <= n; i += Lowbit(i)){
        t[i] += w; 
    }
}

inline ll find(ll pos){
    ll ans = 0;
    for (ll i = pos; i; i -= Lowbit(i)){
        ans += t[i];
    }
    return ans;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    cin >> n;
    for (ll i = 1; i <= n; i ++){
        cin >> a[i].x; a[i].y = i;
    } sort(a + 1, a + 1 + n, cmp);

    for (ll i = 1; i <= n; i ++){
//      cout << a[i].y << " ";
        add(a[i].y, 1);
        ansz += find(a[i].y) - 1;
    }
    cout << ansz;
    return 0;
}

逆序对中有重复的数字

怎么搞


by raccooh @ 2024-07-10 20:12:41

记录重复数字次数然后去重,每次 add 就 add 次数就行。


by raccooh @ 2024-07-10 20:12:50

@kun_shuo


by RedWen_shuo @ 2024-07-10 20:15:09

@raccooh 感谢!!!


|