Minimum Inversion number
Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 18395 Accepted Submission (s): 11168
Problem DescriptionThe Inversion number of a given number sequence A1, A2, ..., the number of pairs (AI, aj) that SA Tisfy i < J and Ai > aj.
For a given sequence of numbers a1, A2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we'll Obtain another sequence. There is totally n such sequences as the following:
A1, A2, ..., An-1, an (where m = 0-the initial seqence)
A2, A3, ..., an, A1 (where m = 1)
A3, A4, ..., an, A1, A2 (where m = 2)
...
An, A1, A2, ..., an-1 (where m = n-1)
You is asked to write a program to find the minimum inversion number out of the above sequences.
Inputthe input consists of a number of test cases. Each case consists of the lines:the first line contains a positive integer n (n <= 5000); The next line contains a permutation of the n integers from 0 to n-1.
Outputfor each case, output the minimum inversion number to a single line.
Sample Input101 3 6 9 0 8 5 7 4 2
Sample Output16
Authorchen, Gaoli
Sourcezoj Monthly, January 2003
RECOMMENDIGNATIUS.L more more next door yny see on the direct violence, of course t (hahaha together laugh him) moving brain, the topic said is a ring then every turn, is equivalent to put the first number to the final consideration of the first number of the original answer to the contribution is a[1]- 1, which is less than its number (the data is a 1 to n arrangement) the last number to the original answer of the contribution of the opposite then the current reverse order after the inverse of the number is subtracted from the first number, plus a number larger than it so that we find a move after the reverse logarithm this time we found the next move directly modify the answer is good, No need to alter the tree array to eject the ans+=n-a[i]-(a[i]-1)
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 #defineLL Long Long5 intbit[5050]={0},n,a[5050];6 inline ll min (ll a,ll b) {7 returnA<b?a:b;8 }9Inlineintlbintx) {Ten returnx& (-x); One } AInline LL Q (intx) { -LL ans=0; - while(x) { theans+=Bit[x]; -x-=lb (x); - } - returnans; + } -InlineintCintx) { + while(x<=N) { Abit[x]++; atx+=lb (x); - } - return 0; - } - intMain () { - while(SCANF ("%d", &n)! =EOF) { inmemset (bit,0,sizeof(bit)); -LL ans=0; to for(intI=1; i<=n;i++){ +scanf"%d",&a[i]); -a[i]++; theANS+=Q (N)-Q (A[i]); * C (A[i]); $ }Panax NotoginsengLL mn=ans; -mn=min (mn,ans); the for(intI=1; i<=n;i++){ +ans+=n-a[i]-(a[i]-1); Amn=min (mn,ans); the } +printf"%lld\n", MN); - } $ $ return 0; -}
[hdu1394] Minimum Inversion Number (tree-like array)