2015 HUAS Summer Trainning #4 A
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
题目大意:求逆序数的个数;
解题思路:因为有时间限制,不能有2层循环来找。需要用到归并排序。
代码:
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 const long long maxn=500000+10; 5 int a[maxn]; 6 long long paisu(int x,int y) 7 { 8 if(x>=y) return 0; 9 long long cnt=0; 10 int m=x+(y-x)/2; 11 cnt+=paisu(x,m); 12 cnt+=paisu(m+1,y); 13 int p2=m+1; 14 for(int p1=x;p1<=m;p1++) 15 { 16 for(int j=p2;j<=y;j++) 17 { 18 if(a[p1]<a[j]) 19 break; 20 else p2++; 21 } 22 cnt+=p2-m-1; 23 } 24 sort(a+x,a+y+1); 25 return cnt; 26 27 } 28 int main() 29 { 30 int i; 31 int n; 32 while(cin>>n&&n) 33 { 34 for(i=0;i<n;i++) 35 cin>>a[i]; 36 cout<<paisu(0,n-1)<<endl; 37 } 38 return 0; 39 }