poj2299 Ultra-QuickSort

来源:互联网 发布:淘宝退货发空包犯法吗 编辑:程序博客网 时间:2024/05/18 15:56

Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KTotal Submissions: 50361 Accepted: 18458

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



离散化+树状数组求逆序对

(离散化用map会超时…)




#include<iostream>#include<cstdio>#include<cmath>#include<algorithm>#include<cstring>#include<cstdlib>#include<map>#define F(i,j,n) for(int i=j;i<=n;i++)#define D(i,j,n) for(int i=j;i>=n;i--)#define LL long long#define MAXN 500005#define pa pair<int,int>using namespace std;int n,b[MAXN],f[MAXN];LL ans;struct data{int val,pos;}a[MAXN];int read(){int ret=0,flag=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-') flag=-1;ch=getchar();}while (ch>='0'&&ch<='9'){ret=ret*10+ch-'0';ch=getchar();}return ret*flag;}void add(int k){for(int i=k;i<=n;i+=i&(-i)) f[i]++;}LL getsum(int k){LL ret=0;for(int i=k;i>0;i-=i&(-i)) ret+=f[i];return ret;}bool cmp(data x,data y){return x.val<y.val;}int main(){n=read();while (n){memset(f,0,sizeof(f));ans=0;F(i,1,n) a[i].val=read(),a[i].pos=i;sort(a+1,a+n+1,cmp);F(i,1,n){if (i>1&&a[i].val==a[i-1].val) b[a[i].pos]=b[a[i-1].pos];else b[a[i].pos]=i;}D(i,n,1){if (b[i]>1) ans+=getsum(b[i]-1);add(b[i]);}printf("%lld\n",ans);n=read();}}


0 0