Ultra-quicksort
Time limit:7000 Ms |
|
Memory limit:65536 K |
Total submissions:39529 |
|
Accepted:14250 |
Description
In this problem, you have to analyze a particle 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 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 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
Note that the result should be stored in long.
#include <stdio.h>#include <string.h>#include <algorithm>#define maxn 500002using std::sort;int tree[maxn], ori[maxn], hash[maxn];long long ans;int getHash(int val, int n){int left = 0, right = n - 1, mid;while(left <= right){mid = (left + right) >> 1;if(val < hash[mid]) right = mid - 1;else if(val > hash[mid]) left = mid + 1;else return mid + 1;}}int lowBit(int pos){ return pos & (-pos); }int getSum(int pos){int sum = 0;while(pos > 0){sum += tree[pos];pos -= lowBit(pos);}return sum;}void update(int pos, int n){ans += (pos - 1 - getSum(pos - 1));while(pos <= n){++tree[pos];pos += lowBit(pos);}}int main(){int n, i;while(scanf("%d", &n), n){for(i = 0; i < n; ++i){scanf("%d", ori + i);hash[i] = ori[i];}sort(hash, hash + n);for(i = 0; i < n; ++i)ori[i] = getHash(ori[i], n);memset(tree, 0, sizeof(tree));ans = 0;for(i = 0; i < n; ++i) update(ori[i], n);printf("%lld\n", ans);}return 0;}