两种方法:
第一种:将总数一半当做背包,用总数-2*最多能装的数目就是所求;
第二种:深搜;
5 5 8 13 27 14
3
#include<stdio.h> #include<cstring> int dp[100005]; int main() { <span style="white-space:pre"> </span>int n, s[25], i, j; <span style="white-space:pre"> </span>while(scanf("%d", &n) == 1){ <span style="white-space:pre"> </span>int sum = 0; <span style="white-space:pre"> </span>for(i = 0; i < n; i ++){ <span style="white-space:pre"> </span>scanf("%d", &s[i]); <span style="white-space:pre"> </span>sum+=s[i]; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>memset(dp, 0, sizeof(dp)); <span style="white-space:pre"> </span>for(i = 0; i < n; i ++){ <span style="white-space:pre"> </span>for(j = sum/2; j >= s[i]; j --) <span style="white-space:pre"> </span>if(dp[j] < dp[j-s[i]]+s[i]) dp[j] = dp[j-s[i]]+s[i]; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>printf("%d\n", sum - 2*dp[sum/2]); <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>return 0; }
#include<cstdio> #include<cstdlib> #define inf 0x7ffff int all, min; int s[25]; void dfs(int sum, int right) { if(right < 0) return; if( abs(all-2*sum) < min ) min = abs(all-2*sum); dfs(sum+s[right], right-1); dfs(sum, right-1); } int main() { int n; while(scanf("%d", &n) == 1){ min = inf; all = 0; for(int i = 0; i < n; i ++){ scanf("%d", &s[i]); all += s[i]; } dfs(0,n-1); printf("%d\n", min); } }
nyoj 325 zb的生日 【DP】||【DFS】,布布扣,bubuko.com
原文地址:http://blog.csdn.net/shengweisong/article/details/38188899