http://poj.org/problem?id=2299
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 62894 | Accepted: 23442 |
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
树状数组+离散化求逆序对
1 #include <algorithm> 2 #include <cstring> 3 #include <cstdio> 4 5 using namespace std; 6 7 const int N(500000); 8 long long ans; 9 int n,tr[N]; 10 struct Node 11 { 12 int num,mark; 13 }a[N]; 14 bool cmp(Node a,Node b) 15 { 16 if(a.num==b.num) 17 return a.mark>b.mark; 18 return a.num>b.num; 19 } 20 21 #define lowbit(x) (x&((~x)+1)) 22 inline void Update(int i,int x) 23 { 24 for(;i<=N;i+=lowbit(i)) tr[i]+=x; 25 } 26 inline int Query(int x) 27 { 28 int ret=0; 29 for(;x;x-=lowbit(x)) ret+=tr[x]; 30 return ret; 31 } 32 33 int main() 34 { 35 for(;scanf("%d",&n)&&n;ans=0) 36 { 37 memset(tr,0,sizeof(tr)); 38 for(int i=1;i<=n;i++) 39 scanf("%d",&a[i].num),a[i].mark=i; 40 sort(a+1,a+n+1,cmp); 41 for(int i=1;i<=n;Update(a[i++].mark,1)) 42 ans+=(long long)Query(a[i].mark); 43 printf("%lld\n",ans); 44 } 45 return 0; 46 }