【POJ】2299 Ultra-QuickSort(逆序对)

http://poj.org/problem?id=2299

在两个元素相同的数列里,其中一个数列要移动到另一个数列相同元素相同的位置,那么要移动的次数就是这个数列关于另一个数列的逆序对数(hash后)

逆序对的求法我原来的博文有 http://www.cnblogs.com/iwtwiioi/p/3523120.html

用归并排序求逆序对,大的在前

左闭右开

#include <cstdio>

#include <cstring>

#include <cmath>

#include <string>

#include <iostream>

#include <algorithm>

using namespace std;

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

#define for1(i,a,n) for(int i=(a);i<=(n);++i)

#define for2(i,a,n) for(int i=(a);i<(n);++i)

#define for3(i,a,n) for(int i=(a);i>=(n);--i)

#define for4(i,a,n) for(int i=(a);i>(n);--i)

#define CC(i,a) memset(i,a,sizeof(i))

#define read(a) a=getint()

#define print(a) printf("%d", a)

#define dbg(x) cout << #x << " = " << x << endl

#define printarr(a, n, m) rep(aaa, n) { rep(bbb, m) cout << a[aaa][bbb]; cout << endl; }

inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; }

inline const int max(const int &a, const int &b) { return a>b?a:b; }

inline const int min(const int &a, const int &b) { return a<b?a:b; }



const int N=500005, oo=~0u>>1;

int a[N], L[N], R[N];

long long cnt;

void gb(int l, int r) {

	if(l<r-1) {

		int m=(l+r)>>1, i, j;

		gb(l, m); gb(m, r);

		for(i=0; i<m-l; ++i) L[i]=a[l+i];

		for(j=0; j<r-m; ++j) R[j]=a[m+j];

		L[i]=R[j]=-oo; i=j=0;

		while(l<r) {

			if(L[i]>R[j]) {

				a[l++]=L[i++];

				cnt+=r-m-j;

			}

			else a[l++]=R[j++];

		}

	}

}

int main() {

	int n;

	while(scanf("%d", &n) && n) {

		cnt=0;

		rep(i, n) read(a[i]);

		gb(0, n);

		printf("%lld\n", cnt);

	}

	return 0;

}

 

 


 

 

Description

【POJ】2299 Ultra-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.

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

你可能感兴趣的:(Quicksort)