poj 2299 Ultra-QuickSort

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

 
题意为给你一串数组,问用冒泡排序多少次可让数组有序(从小到大)
分析题目可知,要想知道次数需算出每个点前有多少个比他大,不妨用树状数组做
思路:先排序用离散化储存,在按顺序把每个点加入树状数组中,然后查询它前面有多少比他小的数,用i减去就是比他大的数。。(我承认讲不清。。。
挂个连接自己看 https://blog.csdn.net/jk_chen_acmer/article/details/79347003
 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
 5 
 6 const int maxn = 5e5+10;
 7 
 8 int n,tree[maxn],id[maxn];
 9 
10 struct node{
11     int val,pos;
12 }in[maxn];
13 
14 bool cmp(node a,node b){
15     return a.val<b.val;
16 }
17 
18 int lowbit(int x){
19     return x&(-x);
20 }
21 
22 void updata(int x,int val){
23     while(x<=n){
24         tree[x]+=val;
25         x+=lowbit(x);
26     }
27 }
28 
29 int getsum(int x){
30     int tot=0;
31     while(x>0){
32         tot+=tree[x];
33         x-=lowbit(x);
34     }
35     return tot;
36 }
37 
38 int main(){
39        // freopen("in.txt", "r", stdin);
40     while(scanf("%d",&n)!=EOF&&n){
41         for(int i=1;i<=n;i++){
42             scanf("%d",&in[i].val);in[i].pos=i;
43         }
44         sort(in+1,in+1+n,cmp);
45         for(int i=1;i<=n;i++){
46             id[in[i].pos]=i;
47         }
48         memset(tree,0,sizeof(tree));
49         long long ans=0;
50         for(int i=1;i<=n;i++){
51             updata(id[i],1);
52             ans+=(i-getsum(id[i]));
53         }
54         printf("%lld
",ans);
55     }
56     return 0;
57 }
View Code
原文地址:https://www.cnblogs.com/plysc/p/10497176.html