POJ 2299 Ultra-QuickSort(树状数组+离散化—求逆序数)

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 52498   Accepted: 19254

Description

POJ 2299 Ultra-QuickSort(树状数组+离散化—求逆序数)_第1张图片 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


题意:将一个不定序序列变为上升序列需要调换两个数的次数?  话说弄一个马桶搋子配图是什么鬼?-_-|||


题解:直接能看出是逆序对的。 不过a[i]的最大值为999999999,没有办法建立树状数组。不过最多才500000个数,我们可以离散化数据。  对i,j我们可以在不改变它们大小关系的情况下改变它们的值。比如1   100000   488888888我们可以离散化为1  2    3。只要不改变它们的大小关系就行了。


代码如下:


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 500010
int bit[maxn],num[maxn],n;
struct node
{
	int val,id;
}a[maxn];

int cmp(node x,node y)
{
	return x.val<y.val;
}

void add(int x)
{
	while(x<=n)
	{
		bit[x]+=1;
		x+= x&-x;
	}
}

long long sum(int x)
{
	long long ans=0;
	while(x>0)
	{
		ans+=bit[x];
		x-= x&-x;
	}
	return ans;
}

int main()
{
	int i;
	while(scanf("%d",&n)&&n)
	{
		for(i=1;i<=n;++i)
		{
			scanf("%d",&a[i].val);
			a[i].id=i;
		}
		sort(a+1,a+n+1,cmp);
		memset(bit,0,sizeof(bit));
		memset(num,0,sizeof(num));
		num[a[1].id]=1;//注意最小的值赋为1 
		for(i=2;i<=n;++i)//离散化过程 
		{
			if(a[i].val==a[i-1].val)
				num[a[i].id]=num[a[i-1].id];
			else
				num[a[i].id]=i;
		}
		long long ans=0;
		for(i=1;i<=n;++i)
		{
			ans+=sum(n)-sum(num[i]);
			add(num[i]);
		}
		printf("%I64d\n",ans);
	}
	return 0;
} 




你可能感兴趣的:(POJ 2299 Ultra-QuickSort(树状数组+离散化—求逆序数))