Topic Links:
http://poj.org/problem?id=2299
Main topic:
Give you a sequence of n integers that can only be exchanged for adjacent numbers and eventually into ascending order, Q: How many interchanges are required at least.
Ideas:
is to ask the number of times the bubble sort is exchanged. In fact, it is to find the inverse number of the original sequence. It can be done with merge sort, line tree, tree array.
But if you do it with a line tree and a tree array, because the number of elements is 500000, but the element value range is 999999999, you need to
To be discretized first. Here is an indirect sort method. Use an array arr[] to store the value of the original sequence, and another array id[] to hold the original sequence number
(1~n), Id[] The order of the arr[] element value from the large to the small, to get the relative size of the array elements (number of arr[). And then use
The tree-like array to find the number of reverse order.
AC Code:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #define LL __ int64using namespace Std;int tree[500050],arr[500050],id[500050],n = 500050;int cmp (const int X,const int y) {return Ar R[X] < arr[y];} int lowbit (int i) {return I & (-i);} void Update (int i,int x) {while (I <= N) {tree[i] = Tree[i] + x; i + = Lowbit (i); }}ll Query (int n) {LL sum = 0; while (n > 0) {sum + = Tree[n]; N-= Lowbit (n); } return sum;} int main () {int N; while (CIN >> n && N) {memset (tree,0,sizeof (Tree)); for (int i = 1; I <= N; ++i) {cin >> arr[i]; Id[i] = i; } sort (id+1,id+n+1,cmp); Indirect sort, get number//for (int i = 1; I <= N; ++i)//cout << Arr[i] << "<< Id[i] << Endl LL ans = 0; for (int i = 1; I <= N; ++i)//reverse order number {Update (id[i],1); Ans + = I-query (Id[i]); } cout << ans << endl; } return 0;}
POJ2299 Ultra-quicksort "tree-like array" "Reverse order Number"