码迷,mamicode.com
首页 > 其他好文 > 详细

2015 HUAS Summer Trainning #4 A

时间:2015-08-07 22:03:44      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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 }
View Code

 

2015 HUAS Summer Trainning #4 A

标签:

原文地址:http://www.cnblogs.com/huaxiangdehenji/p/4711884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!