只过了前面几个 40分,求助大佬们~

P1908 逆序对

ssjl @ 2022-07-14 12:11:02

我用的树状数组+离散化

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#define lowbit(x) x&(-x)

using namespace std;

const int N = 5e5 + 10;

int n;
int a[N];
int d[N];

struct Pro
{
    int val, id;
}z[N];

bool cmp(Pro a, Pro b)
{
    return a.val < b.val;
}

void add(int x, int v)
{
    while(x <= N)
    {
        d[x] += v;
        x += lowbit(x);
    }
}

long long query(int x)
{
    long long res = 0;
    while(x)
    {
        res += d[x];
        x -= lowbit(x);
    }
    return res;
}

void Disc()
{
    sort(z + 1, z + 1 + n, cmp);

    for(int i = 1; i <= n; i ++)
        a[z[i].id] = i;
}

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

    cin >> n;
    for(int i = 1; i <= n; i ++)
        cin >> z[i].val, z[i].id = i;

    Disc();

    long long ans = 0;
    for(int i = 1; i <= n; i ++)
    {
        ans += query(n) - query(a[i]);
        add(a[i], 1);
    }

    cout << ans << endl;

    return 0;
}

by imzzzzzzy @ 2022-07-14 12:59:41

@ssjl 这题不应该是归并吗


by ssjl @ 2022-07-14 14:03:01

@zhangzhengyan123 用树状数组好像也可以求逆序对。


by ssjl @ 2022-07-14 14:21:00

我de出来了哈哈哈,因为可能会有重复元素,相同的数离散化后的值不同,所有相同的数要按照之前的id离散化,防止逆序对数量增多,应该是这样把~

bool cmp(Pro a, Pro b)
{
    if(a.val == b.val)
        return a.id < b.id;
    return a.val < b.val;
}

|