逆序数

来源:互联网 发布:淘宝客联盟社区 编辑:程序博客网 时间:2024/04/29 04:18
Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KTotal Submissions: 60164 Accepted: 22286

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

59105431230

Sample Output

60

Source

Waterloo local 2005.02.05

题目意思:给一个数n,然后n个数,求把这些数排好序按照冒泡排序需要交换的次数

可以用归并排序写

代码;

#include<stdio.h>#include<iostream>#include<algorithm>#include<cstring>#include<queue>using namespace std;int N,A[600066],T[600066];__int64 ans;void Merg_sort(int x,int y){    cout<<" x y "<<x<<" "<<y<<endl;    if(y-x<=1) return;    int mid=x+(y-x)/2;    cout<<" mid "<<mid<<endl;    Merg_sort(x,mid);    Merg_sort(mid,y);    int p=x,q=mid,i=x;    cout<<" p q "<<p<<" "<<q<<endl;    while(p<mid||q<y)    {        if(q>=y||(p<mid&&A[p]<=A[q]))        {T[i++]=A[p++];          cout<<"if "<<i-1<<" "<<T[i-1]<<endl;        }        else        {                if(p<mid)                {ans+=(mid-p);                   cout<<" ans "<<ans<<endl;}                T[i++]=A[q++];                cout<<" else "<<i-1<<" "<<T[i-1]<<endl;        }    }    cout<<" x y "<<x<<" "<<y<<endl;    for(i=x;i<y;i++)    {        A[i]=T[i];        cout<<" A[i] "<<i<<"&"<<A[i]<<" ";    }    cout<<endl;}int main(){    while(~scanf("%d",&N)&&N)    {        memset(A,0,sizeof(A));        memset(T,0,sizeof(T));        for(int i=0;i<N;i++)        {            scanf("%d",&A[i]);        }        ans=0;        Merg_sort(0,N);        printf("%I64d\n",ans);    }    return 0;}

思路就是按照归并排序,合并两个序列时,当第一个数列的数小于第二个数列,那就ans+第一个数列的长度减去i,i为第一个数列中小于第二个数的位置。


0 0
原创粉丝点击