Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9342 Accepted Submission(s): 5739
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 }