POJ2299 Ultra-quicksort "tree-like array" "Reverse order Number"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.