POJ2299 Ultra-QuickSort

 

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 53685   Accepted: 19722

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

Source

 

归并排序求逆序对。

归并排序分分钟写完,但是longlong忘了用lld输出,又浪费了一阵子青春

 

 1 #include<algorithm>
 2 #include<cstdio>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<cmath>
 6 using namespace std;
 7 const int mxn=520000;
 8 long long a[mxn],t[mxn];
 9 int n;
10 long long ans;
11 void msort(int l,int r){
12     if(r-l>1)
13     {
14         int mid=l+(r-l)/2;
15         msort(l,mid);
16         msort(mid,r);
17         int p=l,q=mid,i=l;//指向起点 
18         while(p<mid || q<r){//范围内有数就继续处理 
19             if(q>=r || (p<mid && a[p]<=a[q]))
20             {
21                 t[i++]=a[p++];
22             }
23             else {t[i++]=a[q++];ans+=mid-p;};
24         }
25         for(i=l;i<r;i++)a[i]=t[i];//用排序后的序列覆盖原数组对应部分 
26     }
27     return;
28 }
29 int main(){
30     while(scanf("%d",&n) && n){
31         ans=0;
32         int i,j;
33         for(i=1;i<=n;i++)scanf("%lld",&a[i]);
34         msort(1,n+1);
35         printf("%lld\n",ans);
36     }
37     return 0;
38 }

 

posted @ 2016-07-03 21:50  SilverNebula  阅读(129)  评论(0编辑  收藏  举报
AmazingCounters.com