南阳325----zb的生日
1 //重量太大,用01背包容易超时 2 //数据只有20组。可以用dfs搜索最优解 3 #include<stdio.h> 4 int a[25]; 5 int maxs,n,s; 6 void dfs(int,int); 7 int main() 8 { 9 int i; 10 while(~scanf("%d",&n)) 11 { 12 for(i=s=0; i<n; ++i) 13 { 14 scanf("%d",a+i); 15 s+=a[i]; 16 } 17 maxs=0; 18 dfs(0,0); 19 printf("%d\n",(s-maxs)-maxs); 20 } 21 } 22 void dfs(int x,int sum) 23 { 24 if(x>n) 25 return ; 26 if(sum*2 <= s) 27 { 28 if(sum>maxs) 29 maxs=sum; 30 } 31 else return ; 32 33 dfs(x+1,sum); 34 dfs(x+1,sum+a[x]); 35 } 36 37 //最优解,逆序剪枝 38 #include <stdio.h> 39 #define max(a,b) a>b?a:b 40 int V,ans,n,w[21],sum[21]; 41 void dfs(int i,int cnt) 42 { 43 if(i == 0) 44 { 45 ans = max(ans,cnt); 46 return ; 47 } 48 if(ans == V || cnt+sum[i] <= ans) //cut 49 return ; 50 if(cnt+w[i] <= V) 51 dfs(i-1,cnt+w[i]); 52 dfs(i-1,cnt); 53 } 54 int main() 55 { 56 while(~scanf("%d",&n)) 57 { 58 ans = 0; 59 for(int i=1;i<=n;i++) 60 { 61 scanf("%d",&w[i]); 62 sum[i] = sum[i-1] + w[i]; 63 } 64 V = sum[n]/2; 65 dfs(n,0); 66 printf("%d\n",sum[n]-2*ans); 67 } 68 return 0; 69 } 70