poj 2299 Ultra-QuickSort(樹狀數組)
阿新 • • 發佈:2018-05-01
mem AC get owb ios void ron esp swap Ultra-QuickSort
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.
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.
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 67681 | Accepted: 25345 |
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 sequenceUltra-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
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
思路;
樹狀數組裸題,逆序對思想,離散化處理
每插入一個點,查詢下在這個點之前還有多少個點沒被插入,這些點的數量就是逆序對的數量,也就是需要移動的步數當然也可以用線段樹寫,只不過要多敲點。。
實現代碼:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<iostream> #include<cstring> #include<algorithm> #include<cstdio> using namespace std; #define ll long long #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define mid int m = (l + r) >> 1 const int M = 5e5 + 10; const double EPS = 1e-8; //inline int sgn(double x) return (x > EPS) - (x < -EPS); //浮點數比較常數優化寫法 int b[M],c[M],n; int lowbit(int x){ return x&(-x); } int getsum(int x){ int sum = 0; while(x>0){ sum += c[x]; x -= lowbit(x); } return sum; } void update(int x,int value){ while(x<=n){ c[x] += value; x += lowbit(x); } } struct node{ int id,val; }a[M]; bool cmp(node x,node y){ return x.val < y.val; } int main() { while(scanf("%d",&n)&&n){ memset(c,0,sizeof(c)); for(int i = 1;i <= n;i ++){ scanf("%d",&a[i].val); a[i].id = i; } sort(a+1,a+n+1,cmp); for(int i = 1;i <= n;i ++) b[a[i].id] = i; ll ans = 0; for(int i = 1;i <= n;i ++){ update(b[i],1); ans += i-getsum(b[i]); } cout<<ans<<endl; } return 0; }
poj 2299 Ultra-QuickSort(樹狀數組)