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.划分问题 2.递归求解. 3.合并
代码及步骤分析:
 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 const int maxn=500005;
 5 int a[maxn],b[maxn];
 6 long long k;
 7 
 8 int merge_sort(long long x,long long y)
 9 {
10     if(x<y)
11     {
12         long long m=(x+y)/2;   //划分区间
13         merge_sort(x,m);       //划分并递归求解
14         merge_sort(m+1,y); 
15         int p=0,i=x,j=m+1;
16         while(i<=m && j<=y)    //划分的数组两边都非空时
17         {
18             if(a[i]>a[j])     //找到划分后的数组左边的数大于右边的数时
19             {
20                 b[p++]=a[j++];//  将左边数组复制到临时空间
21                 k+=m+1-i;      //注意此时k值的记录!!!
22             }
23             else
24                 b[p++]=a[i++];   //将右边数组复制到临时空间
25             
26         }
27         while(i<=m)
28             b[p++]=a[i++];   
29         while(j<=y)
30             b[p++]=a[j++];
31         for(i=0;i<p;++i)
32             a[x+i]=b[i];
33         
34     }
35     return 0;
36 }
37 
38 int main()
39 {
40     long long n,i;
41     while(scanf("%lld",&n) && n)
42     {   
43         k=0;  //定义k记录交换次数
44         for(i=0;i<n;i++)
45             scanf("%lld",&a[i]);
46         merge_sort(0,n-1);   
47         printf("%lld\n",k);
48     }
49     
50     return 0;
51 }

归并排序时间复杂度为O(nlogn),统计改变次数k也并不改变其时间复杂度。
 
 
posted on 2015-08-05 08:46  xx-sisley  阅读(137)  评论(0编辑  收藏  举报