Hdu1394 calculate the number of reverse orders using a tree Array

Source: Internet
Author: User

 

A sequence composed of 0 .. n-1. Each time, you can move the first element of the team to the end of the team to find the number of minimum reverse pairs of the N sequences.
Algorithm :
Returns the reverse order of a tree array. When element I is added, the value of a [I] under element I is + 1, from the end of the team to the first of the team,
The logarithm of the reverse order + = getsum (I-1) when you join the queue, that is, the number of elements whose subscript is greater than it but whose value is smaller than it.
Because the tree array cannot process the element whose subscript is 0, when each element enters the + 1, the corresponding other Program You must also adjust it accordingly.
After finding the number of reverse pairs of the original sequence, move the first element to the end of the team. The reverse logarithm is

The original reverse logarithm + number of elements greater than I-number of elements smaller than I, because it is 0 .. n, it is easy to calculate directly, every time you update Min.

# Include <stdio. h> # define maxn 10000int C [maxn], a [maxn], n; int min (int A, int B) {if (a <B) return; else return B;} int lowbit (int I) {return I &-I;} void Update (int I, int X) {While (I <= N) {c [I] + = x; I + = lowbit (I) ;}} int getsum (INT X) {int sum = 0; while (x> 0) {sum + = C [X]; X-= lowbit (x);} return sum;} int main () {While (scanf ("% d", & N) = 1) {for (INT I = 1; I <= N; I ++) C [I] = 0; int sum = 0; For (INT I = 1; I <= N; I ++) {scanf ("% d", & A [I]) ;}for (INT I = N; I> = 1; I --) {update (A [I] + 1, 1); sum + = getsum (A [I]);} int ans = sum; For (INT I = 1; I <= N; I ++) {sum = sum-A [I] + (n-A [I]-1); ans = min (ANS, sum );} printf ("% d \ n", ANS);} return 0 ;}

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.