【POJ2266】【树状数组+离散化】Ultra-QuickSort
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
【分析】
开始离散化用MAP T了半天,不活了..
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <vector> 6 #include <utility> 7 #include <iomanip> 8 #include <string> 9 #include <cmath> 10 #include <map> 11 12 const int MAXN = 500000 + 10; 13 const int MAXM = 500000 + 10; 14 //const int MAXM = 2000 + 10; 15 const int MAXL = 10; 16 using namespace std; 17 struct DATA{ 18 int val; 19 int order; 20 bool operator < (DATA b)const{ 21 return val < b.val; 22 } 23 }rem[MAXN]; 24 typedef long long ll; 25 int n; 26 int data[MAXN]; 27 int C[MAXN]; 28 29 void init(){ 30 for (int i = 1; i <= n; i++) { 31 scanf("%d", &data[i]); 32 C[i] = 0; 33 rem[i].val = data[i]; 34 rem[i].order = i; 35 } 36 sort(rem + 1, rem + 1 + n); 37 for (int i = 1; i <= n; i++) data[rem[i].order] = i; 38 //for (int i = 1; i <= n; i++) printf("%d\n", data[i]);printf("\n"); 39 } 40 int lowbit(int x){return x&-x;} 41 int sum(int x){ 42 int cnt = 0; 43 while (x > 0){ 44 cnt += C[x]; 45 x -= lowbit(x); 46 } 47 return cnt; 48 } 49 void add(int x){ 50 while (x <= n){ 51 C[x]++; 52 x += lowbit(x); 53 } 54 return; 55 } 56 57 void work(){ 58 ll Ans = 0; 59 //前面共 i - 1个数字 60 for (int i = 1; i <= n; i++){ 61 Ans += (i - 1 - sum(data[i]));//严格大于 62 add(data[i]); 63 } 64 printf("%lld\n", Ans); 65 } 66 67 int main(){ 68 #ifdef LOCAL 69 freopen("data.txt", "r", stdin); 70 freopen("out.txt", "w", stdout); 71 #endif 72 while (scanf("%d", &n) && n){ 73 init(); 74 work(); 75 } 76 return 0; 77 } 78