题目地址:点击打开链接
思路:价值和的一半为一个背包,往里面放东西就行了,刚开始输出搞错了,结果用搜索做超时了
AC代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> typedef long long ll; using namespace std; int value[110]; int dp[100010]; int main() { int t,n; int i,j,sum; scanf("%d",&t); while(t--) { memset(dp,0,sizeof(dp)); sum = 0; scanf("%d",&n); for(i=0; i<n; i++) { scanf("%d",&value[i]); sum += value[i]; } int m = sum / 2; for(i=0; i<n; i++) { for(j=m; j>=value[i]; j--) { dp[j] = max(dp[j],dp[j-value[i]] + value[i]); } } printf("%d\n",abs(sum-2*dp[m])); } return 0; }
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> typedef long long ll; using namespace std; int m,n,sum; int value[110]; int visit[110]; int flag; void dfs(int st,int sum1) { int i; for(i=st; i<n; i++) { if(!visit[i]) { if(sum1 + value[i] < m) { visit[i] = 1; dfs(i+1,sum1+value[i]); visit[i] = 0; } if(sum1 + value[i] >= m) { if(abs(sum-2*(sum1+value[i])) < flag) flag = abs(sum-2*(sum1+value[i])); while(value[i] == value[i+1]) i++; } } } } int main() { int t; int i; scanf("%d",&t); while(t--) { memset(visit,0,sizeof(visit)); sum = 0; scanf("%d",&n); for(i=0; i<n; i++) { scanf("%d",&value[i]); sum += value[i]; } m = sum / 2; flag = 10000000; dfs(0,0); printf("%d\n",flag); } return 0; }