标签:des style blog http color java os io
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10477 Accepted Submission(s): 6464
1 #include<cstdio> 2 #include<cstring> 3 #include<stdlib.h> 4 #include<algorithm> 5 using namespace std; 6 int a[5005]; 7 int main() 8 { 9 int n,i,j; 10 while(scanf("%d",&n)!=EOF) 11 { 12 int sum=0; 13 for(i=0;i<n;i++) 14 { 15 scanf("%d",&a[i]); 16 for(j=0;j<i;j++) 17 if(a[j]>a[i]) 18 sum++; 19 } 20 int ans=sum; 21 for(i=0;i<n;i++) 22 { 23 sum=sum-a[i]+(n-a[i]-1); 24 if(sum<ans) 25 ans=sum; 26 } 27 printf("%d\n",ans); 28 } 29 return 0; 30 }
2.线段树
同样的一开始也是要找出逆序数的对数,暴力方法是从第一个数到现在这个数扫一遍查找,线段树的方法就是用线段树去查询,会更快
后面对新序列的逆序数对数的处理时相同的
线段树的代码
1 #include<cstdio> 2 #include<cstring> 3 #include<stdlib.h> 4 #include<algorithm> 5 using namespace std; 6 struct node 7 { 8 int l,r; 9 int num; 10 int mid() 11 { 12 return (l+r)>>1; 13 } 14 }a[5000*4]; 15 int b[5005]; 16 void btree(int l,int r,int step) 17 { 18 a[step].l=l; 19 a[step].r=r; 20 a[step].num=0; 21 if(l==r) return ; 22 int mid=a[step].mid(); 23 btree(l,mid,step*2); 24 btree(mid+1,r,step*2+1); 25 } 26 27 void ptree(int step,int vis) 28 { 29 a[step].num++; 30 if(a[step].l==a[step].r) return ; 31 int mid=a[step].mid(); 32 if(vis>mid) 33 ptree(step*2+1,vis); 34 else 35 ptree(step*2,vis); 36 } 37 38 int fintree(int step,int x,int y) 39 { 40 if(a[step].l==x&&a[step].r==y) 41 return a[step].num; 42 int mid=a[step].mid(); 43 if(x>mid) 44 return fintree(step*2+1,x,y); 45 else if(y<=mid) 46 return fintree(step*2,x,y); 47 else 48 return fintree(step*2,x,mid)+fintree(step*2+1,mid+1,y); 49 } 50 int main() 51 { 52 int n,i,j; 53 while(scanf("%d",&n)!=EOF) 54 { 55 int ans=0; 56 btree(0,n-1,1); 57 for(i=0;i<n;i++) 58 { 59 scanf("%d",&b[i]); 60 ans+=fintree(1,b[i],n-1); 61 ptree(1,b[i]); 62 } 63 int minn=ans; 64 for(i=0;i<n;i++) 65 { 66 ans=ans-b[i]+(n-1-b[i]); 67 if(minn>ans) minn=ans; 68 } 69 printf("%d\n",minn); 70 } 71 return 0; 72 }
HDU 1394 Minimum Inversion Number,布布扣,bubuko.com
HDU 1394 Minimum Inversion Number
标签:des style blog http color java os io
原文地址:http://www.cnblogs.com/clliff/p/3895053.html