Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 70489 | Accepted: 26437 |
Description
![](http://poj.org/images/2299_1.jpg)
Ultra-QuickSort produces the output
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
//求逆序对
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <algorithm> 6 using namespace std; 7 #define ll long long 8 #define N 500009 9 #define gep(i,a,b) for(ll i=a;i<=b;i++) 10 #define mem(a,b) memset(a,b,sizeof(a)) 11 #define lowbit(x) x&(-x) 12 ll c[N],a[N],n;//一定要用ll 13 struct Node{ 14 ll id,val; 15 }nod[N]; 16 void update(ll i,ll num) 17 { 18 while(i<=n){ 19 c[i]+=num; 20 i+=lowbit(i); 21 } 22 } 23 ll getsum(ll n) 24 { 25 ll sum=0; 26 while(n>0){ 27 sum+=c[n]; 28 n-=lowbit(n); 29 } 30 return sum; 31 } 32 bool cmp(Node a,Node b) 33 { 34 return a.val<b.val; 35 } 36 int main() 37 { 38 while(~scanf("%lld",&n)&&n){ 39 mem(a,0); 40 mem(c,0); 41 gep(i,1,n){ 42 scanf("%lld",&nod[i].val); 43 nod[i].id=i; 44 } 45 sort(nod+1,nod+1+n,cmp);//要先排序 46 int x=1; 47 gep(i,1,n) 48 { 49 a[nod[i].id]=x; 50 if(nod[i+1].val!=nod[i].val){//离散化 51 x++; 52 } 53 } 54 ll ans=0; 55 gep(i,1,n){ 56 update(a[i],1); 57 ans+=getsum(n)-getsum(a[i]);//左边比我大的数的数目 58 } 59 printf("%lld ",ans); 60 } 61 return 0; 62 }