Ultra-quicksort
Time Limit: 7000MS |
|
Memory Limit: 65536K |
Total Submissions: 43339 |
|
Accepted: 15798 |
Description
In this problem, you has to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping, 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 what many swap operations Ultra-quicksort needs to perform in order to sort a given input sequenc E.
Input
The input contains several test cases. Every test case begins with a line this contains a single integer n < 500,000-the length of the input sequence. Each of 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 is processed.
Output
For every input sequence, your program prints a single line containing an integer number OP, the minimum number of swap op Erations necessary to sort the given input sequence.
Sample Input
59105431230
Sample Output
60
Since sophomore, it seems that only a line tree has not been written in a tree-like array ... Take a practiced hand of the problem of reverse order
#include <cstdio> #include <iostream> #include <cstring> #include <cstdlib> #include < algorithm> #include <cmath> #include <queue> #include <deque> #include <set> #include <map > #include <ctime> #define LL long long#define INF 0x7ffffff#define pa pair<int,int> #define Pi 3.1415926535897932384626433832795028841971using namespace Std;inline ll read () {ll x=0,f=1;char Ch=getchar (); while (ch< ' 0 ' | | Ch> ' 9 ') {if (ch== '-') F=-1;ch=getchar ();} while (ch>= ' 0 ' &&ch<= ' 9 ') {x=x*10+ch-' 0 '; Ch=getchar ();} return x*f;} struct Dat{int a,rnk;} A[500010];int d[500010];int C[500010];bool operator < (const dat &a,const dat &b) {return A.A<B.A;} int n,cnt; LL ans;inline int lowbit (int x) {return x& (-X);} inline int Change (int. x) {for (int i=x;i<=n;i+=lowbit (i)) c[i]++;} inline int query (int x) {int sum=0;for (int i=x;i;i-=lowbit (i)) Sum+=c[i];return sum;} int main () {while (scanf ("%d", &n) &&n) {for (int i=1;i<=n;i++)A[i].a=read (), A[i].rnk=i;sort (a+1,a+n+1), cnt=ans=0;a[0].a=-1;for (int i=1;i<=n;i++) {if (A[I].A!=A[I-1].A) cnt++ ; d[a[i].rnk]=cnt;} Memset (C,0,sizeof (c)); for (int i=n;i>=1;i--) {ans+=query (d[i]); Change (D[i]);} printf ("%lld\n", ans);}}
poj2299 Ultra-quicksort