OpenJ_Bailian - 2299Ultra-QuickSort 【树状数组+离散化】

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence 

9 1 0 5 4 ,


Ultra-QuickSort produces the output 

0 1 4 5 9 .


Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

思路:就是让你求逆序对,上次是用归并排序来写的,这次用的树状数组来写的,复杂度都是O(n),但个人认为还是树状数组略方便,用树状数组求逆序对就是每次都更新1,然后每次相加i-sum[i],就是前面有多少数比它大。

这题需要离散化处理一下数据,防止数据过大爆(好像有人没有离散化也可以过)。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e5 + 10;
int c[maxn], p[maxn];
int n;
struct node
{
    int val, pos;
    bool operator < (const node &r)
    {
        return val < r.val;
    }
}a[maxn];

int lowbit(int i)
{
    return i & -i;
}
void update(int i)
{
    while(i <= n)
    {
        c[i]++;
        i += lowbit(i);
    }
}
int sum(int i)
{
    int ans = 0;
    while(i > 0)
    {
        ans += c[i];
        i -= lowbit(i);
    }
    return ans;
}

int main()
{
    while(~scanf("%d", &n) && n)
    {
        memset(c, 0, sizeof(c));
        for(int i = 1; i <= n; ++i)
        {
            scanf("%d", &a[i].val);
            a[i].pos = i;
        }
        sort(a + 1, a + n + 1);
        for(int i = 1; i <= n; ++i)
        {
            p[a[i].pos] = i;
        }
        ll ans = 0;
        for(int i = 1; i <= n; ++i)
        {
            update(p[i]);
            ans += i - sum(p[i]);
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值