您的位置:首页 > 产品设计 > UI/UE

POJ 2299 Ultra-QuickSort【逆序数&&离散化】

2016-08-12 21:16 483 查看
Ultra-QuickSort

Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 55493 Accepted: 20471
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 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.
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

Source

Waterloo local 2005.02.05
可以跳过的碎碎念:

这些题做着真是感觉到了心灵的释放,整个理解了之后做出来感觉好爽啊,好爽……!

题解

这个题是求逆序数,拆开来说涉及到了两个点,一个是树状数组(求逆序数还有另一种做法是归并排序,这里我没用,所以就不说了),一个是离散化

用了离散化之后,把使用给出的数列转化为了使用各个数在给出顺序中排好编号后对于数字再升序排列所得出的数列。(详解1中有用例子解释)

逆序数的概念:

对于n个不同的元素,先规定各元素之间有一个标准次序(例如n个 不同的自然数,可规定从小到大为标准次序),于是在这n个元素的任一排列中,当某两个元素的先后次序与标准次序不同时,就说有1个逆序。一个排列中所有逆序总数叫做这个排列的逆序数。

关于这个题目的详解,可以先看这个:详解1号(这个是我的同学写的,对于离散化和树状数组求逆序数的方法举了个例子,解释的语言更加易懂

然后再看这个:详解2号(这是我百度出来的,我觉得相对于我同学写的,这个方法更加奇特?有趣?在理解离散化和树状数组如何求逆序数后,我是看这个题解理解这道题的。)

总之两个方法用哪个都没有问题。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 500000+10
int c
,re
,n;

struct str
{
int x,y;
}a
;

bool cmp(str a,str b)
{
return a.x<b.x;
}

int lowbit(int x)
{
return x&(-x);
}
void update(int x)
{
while(x<=n)
{
c[x]+=1;//表示这个数加入树状数组
x+=lowbit(x);
}
}
int sum(int x)
{
int s=0;
while(x>0)
{
s+=c[x];
x-=lowbit(x);//把这个数从树状数组中删去
}
return s;
}
int main()
{
int i;
while(scanf("%d",&n),n)
{
memset(c,0,sizeof(c));
for(i=1;i<=n;i++)
{
scanf("%d",&a[i].x);
a[i].y=i;
}
sort(a+1,a+n+1,cmp);
for(i=1;i<=n;i++)
re[a[i].y]=i;
__int64 ans=0;
for(i=1;i<=n;i++)
{
update(re[i]);
ans+=i-sum(re[i]);
}
printf("%I64d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: