poj 2299 Ultra-QuickSort 树状数组求解逆序数

本文介绍了一种利用树状数组计算数组逆序数的方法。通过将问题转化为求解已点亮且编号较大的灯的数量,进而计算出总的逆序数。文章提供了完整的代码实现,并解释了关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
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 sequence9 1 0 5 4 ,Ultra-QuickSort produces the output0 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.

Input
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 – the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0
题意:给出n个数保存在数组a[n]中,求解该数组的逆序数,逆序数定义:在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。逆序数为偶数的排列称为偶排列;逆序数为奇数的排列称为奇排列。如2431中,21,43,41,31是逆序,逆序数是4,为偶排列。
思路:比较经典的一道树状数组题目,我们可以将问题抽象变形一下,有一排编号为1-n的灯,依次点亮a[0],a[1]…a[n-1]号灯;问当点亮a[i]号灯时,已经点亮且编号大于a[i]号灯的个数,这个个数就是a[i]的逆序数,那么如何来计算呢?假设我们现在有一组初始值均为0的数组p[n],当点亮a[i]号灯时,就另p[a[i]-1]=1;那么在点亮a[i]号灯时已经点亮了i盏灯(注意,a是从0开始记的,a[i]是第i+1盏灯),然后再计算一下sum(p[0,1…a[i]-1])就是已经点亮的等中编号小于a[i]的灯的个数,因为一共点亮了i盏灯,所以i-sum(p[0,1…a[i]-1])就是已经点亮且编号大于a[i]号灯的个数,这样把对i-sum(p[0…a[i]-1)求和就是答案了,这道题还需要注意的就是题目中所给的数字并不一定连续切范围较大,所以需要离散化一下;

#include<stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX_N=500005;
int N,b[MAX_N],k[MAX_N];
struct Node
{
    int val,key;
    bool operator <(Node a){return val<a.val;}
}num[MAX_N];

void add(int i,int x)
{
    while(i<=N)
    {
        b[i]+=x;
        i+=i&-i;
    }
}
int sum(int i)
{
    int s=0;
    while(i>0)
    {
        s+=b[i];
        i-=i&-i;
    }
    return s;
}
int main()
{
    //freopen("test.txt","r",stdin);
    while(scanf("%d",&N)&&N)
    {
        for(int i=0;i<N;i++)
        {
            scanf("%d",&num[i].val);
            num[i].key=i;
        }
        sort(num,num+N);
        for(int i=0;i<N;i++)
        {
            k[num[i].key]=i+1;//离散
            b[i]=0;
        }
        b[N]=0;
        long long ans=0;
        for (int i=0;i<N;i++)
        {
            ans+=i-sum(k[i]);
            add(k[i],1);
        }
        printf("%lld\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值