POJ2299 Ultra-QuickSort(树状数组+离散化)

POJ2299 Ultra-QuickSort

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

题解

题意

对于给定序列,问至少需要交换多少次才能够转变为非递减序列。

思路

实际上,了解逆序数后应该可以明白这样一个问题,逆序数实际上衡量的是这样一个问题,当进行有效交换之后,相当于逆序数减少了1。因此,统计序列的逆序数可以得到最终结果。

统计逆序数时,可以采用归并排序过程中进行统计。当进行归并排序时,由于分成两组,分别向最终序列内进行添加。所以在此过程中可以统计逆序数。

另外,通过树状数组的方式也能够统计逆序数。当然,题目内有这样的情况,由于取值范围非常大。所以需要进行离散化的操作。然后按照逆序数的定义,统计逆序数。

代码

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;

#define REP(i,n) for(int i=0;i<(n);i++)

const int MAXN = 5e5+10;
ll ind[MAXN];
ll C[MAXN];

struct Node{
	ll v;
	ll p;
}a[MAXN];

ll N;


ll lowbit(ll x){
	return x&(-x);
}


ll getsum(ll i){
	ll ans = 0;
	for(;i;i-=lowbit(i)){
		ans += C[i];
	}
	
	return ans;
}

ll add(ll i,ll val){
	for(ll x=i;x<=N;x+=lowbit(x)){
		C[x]+=val;
	}
	return 0;
}

ll cmp1(Node a,Node b){
	return a.v<b.v;
}

void init(){
	memset(C,0,sizeof(C));
	memset(ind,0,sizeof(ind));
	memset(a,0,sizeof(a));
}

int main(){
	while(~scanf("%d",&N)&&N){
		init();
		for(int i=1;i<=N;i++){
			scanf("%d",&a[i].v);
			a[i].p = i;
		}
		sort(a+1,a+N+1,cmp1);
		for(int i=1;i<=N;i++){
			ind[a[i].p] = i;
		}
		ll ans=0;
        for(int i=1;i<=N;i++){
            add(ind[i],1);
            ans+=i-getsum(ind[i]);
        }
        printf("%lld\n",ans);
	}
	
	return 0;
}
posted @ 2018-08-21 17:04  caomp  阅读(134)  评论(0)    收藏  举报