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

POJ - 2299 Ultra-QuickSort

时间:2017-08-16 10:01:55      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:cas   --   hat   wap   str   operation   enc   ppi   case   

 

 

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

标签:cas   --   hat   wap   str   operation   enc   ppi   case   

原文地址:http://www.cnblogs.com/xibeiw/p/7371371.html

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