Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 9342 Accepted Submission(s): 5739
Problem Description
The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy 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 will obtain another sequence. There are 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 are asked to write a program to find the minimum inversion number out of the above sequences.
Input
The input consists of a number of test cases. Each case consists of two 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.
Output
For each case, output the minimum inversion number on a single line.
Sample Input
10
1 3 6 9 0 8 5 7 4 2
Sample Output
16
Author
CHEN, Gaoli
Source
代码:
1 //线段树实现单点更新,并求和
2 #include<stdio.h>
3 #define maxn 5001
4 struct node{
5 int lef,rig,sum;
6 int mid(){ return lef+((rig-lef)>>1) ;}
7 };
8 node seg[maxn<<2];
9 int aa[maxn+3];
10 void build(int left,int right,int p )
11 {
12 seg[p].lef=left;
13 seg[p].rig=right;
14 seg[p].sum=0;
15 if(left==right) return ;
16 int mid=seg[p].mid();
17 build(left,mid,p<<1);
18 build(mid+1,right,p<<1|1);
19 }
20 void updata(int pos,int p,int val)
21 {
22 if(seg[p].lef==seg[p].rig)
23 {
24 seg[p].sum+=val;
25 return ;
26 }
27 int mid=seg[p].mid();
28 if(pos<=mid) updata(pos,p<<1,val);
29 else updata(pos,p<<1|1,val);
30 seg[p].sum=seg[p<<1].sum+seg[p<<1|1].sum;
31 }
32 int query(int be ,int en,int p)
33 {
34 if(be<=seg[p].lef&&seg[p].rig<=en)
35 return seg[p].sum;
36 int mid=seg[p].mid();
37 int res=0;
38 if(be<=mid) res+=query(be ,en ,p<<1);
39 if(mid<en) res+=query(be ,en ,p<<1|1);
40 return res;
41 }
42 int main()
43 {
44 int nn,i,ans;
45 while(scanf("%d",&nn)!=EOF)
46 {
47 ans=0;
48 build(0,nn-1,1);
49 for(i=1;i<=nn;i++)
50 {
51 scanf("%d",&aa[i]);
52 updata(aa[i],1,1);
53 if(aa[i]!=nn-1) ans+=query(aa[i]+1,nn-1,1); //统计比其大的数
54 }
55 int min=ans;
56 for(i=1;i<=nn;i++)
57 {
58 ans+=nn-2*aa[i]-1;
59 if(min>ans) min=ans;
60 }
61 printf("%d\n",min);
62 }
63 return 0 ;
64 }