[POJ 2299]Ultra-QuickSort

来源:互联网 发布:安卓gal软件 编辑:程序博客网 时间:2024/06/03 16:46

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

tips:题面右边有个马桶塞不知道想表达什么。

简述题意,求一个数列的逆序对数量。多组数据,每组数据第一行一个n,接下来n行是这个数列。

题解:
由于a[i]很大,所以我们就不能用树状数组了。我们就得用归并排序来统计逆序对数量。

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<algorithm>#define ll long long#define LiangJiaJun main#define eps 1e-9using namespace std;int a[500004],temp[500004],n;ll ans=0;int combi(int l,int m,int r){    int i=l,j=m+1,k=l;    while(i<=m&&j<=r){        if(a[i]>a[j]){            ans+=(m-i+1);            temp[k++]=a[j++];        }        else temp[k++]=a[i++];    }    while(i<=m)temp[k++]=a[i++];    while(j<=r)temp[k++]=a[j++];    for(i=l;i<=r;i++)a[i]=temp[i];    return 0;}int erfen(int l,int r){    if(r<=l)return 0;    int mid=(l+r)>>1;    erfen(l,mid);    erfen(mid+1,r);    combi(l,mid,r);}int LiangJiaJun(){    while(scanf("%d",&n)!=EOF){        ans=0;        if(n == 0)break;        for(int i=1;i<=n;i++)scanf("%d",&a[i]);        erfen(1,n);        printf("%lld\n",ans);    }    return 0;}
原创粉丝点击