POJ - 2299 Ultra-QuickSort

Posted 西北会法语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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


题目的意思是求一个数列的逆序数,用树状数组可以直接模拟出来。
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 
 6 using namespace std;
 7 
 8 const int maxn=500005;
 9 int c[maxn],d[maxn],g[maxn];
10 
11 void update(int x,int v)
12 {
13     for(;x<=maxn;x+=x&(-x))
14         g[x]+=v;
15 }
16 
17 int getsum(int x)
18 {
19     int sum=0;
20     for(;x>0;x-=x&(-x))
21         sum+=g[x];
22     return sum;
23 }
24 
25 int main()
26 {
27     int n;
28     while(~scanf("%d",&n),n)
29     {
30         memset(c,0,sizeof(c));
31         memset(d,0,sizeof(d));
32         memset(g,0,sizeof(g));
33         for(int i=0;i<n;i++)
34         {
35             scanf("%d",&c[i]);
36             d[i]=c[i];
37         }    
38         sort(d,d+n); 
39         int size=unique(d,d+n)-d;
40         for(int i=0;i<n;i++)
41             c[i]=lower_bound(d,d+n,c[i])-d+1;
42         /*for(int i=1;i<=n;i++)
43             cout<<c[i]<<" ";*/
44         long long ans=0;
45         for(int i=0;i<n;i++)
46         {
47             update(c[i],1);
48             ans+=i+1-getsum(c[i]);
49         }
50         printf("%lld\n",ans);
51     }
52     
53     
54     return 0;    
55 } 

 

以上是关于POJ - 2299 Ultra-QuickSort的主要内容,如果未能解决你的问题,请参考以下文章

POJ——T 2299 Ultra-QuickSort

POJ 2299.Ultra-QuickSort

poj2299(归并排序求逆序对)

POJ 2299 Ultra-QuickSort

POJ2299 Ultra-QuickSort

poj2299 Ultra-QuickSort