标签:
2 5 2 6 5 8 9 3 2 1 5
0 2
可参考:http://blog.csdn.net/dgq8211/article/details/7720729
解题思路:以苹果总量的一半sum/2为背包容量。让背包价值最大,对于当前苹果选择放还是不放。这里有用到剪枝:
可行性:如果将物品装入背包后,费用超过容量,则不将它放入背包。
最优性:1、如果背包已经装满,则不再考虑其他情况。
2、如果背包中已有物品加上现有可选物品的总重量都不大于已知的最优解,则剪枝。
#include<bits/stdc++.h> using namespace std; const int maxn=1010; int V,ans; int sum[maxn],a[maxn]; void dfs(int cur,int res){ if(cur==0){ //搜索终点 ans=ans>res?ans:res; return ; } if(ans==V||res+sum[cur]<ans){ //最优性剪枝 return ; } if(res+a[cur]<=V) //可行性剪枝 dfs(cur-1,res+a[cur]); dfs(cur-1,res); } int main(){ int t,n,i,j,k; scanf("%d",&t); while(t--){ sum[0]=0; scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&a[i]); sum[i]=sum[i-1]+a[i]; } V=sum[n]/2; ans=0; dfs(n,0); printf("%d\n",sum[n]-2*ans); } return 0; }
nyoj 456——邮票分你一半——————【背包思想搜索】
标签:
原文地址:http://www.cnblogs.com/chengsheng/p/4524644.html