标签:
5 5 8 13 27 14
3
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 #define max(a,b) a>b?a:b 5 using namespace std ; 6 int main() 7 { 8 int num[25] ; 9 int dp[100005] ; 10 int i, j, n ; 11 while(~scanf("%d", &n)) 12 { 13 memset(dp, 0,sizeof(dp)) ; 14 int sum = 0 ; 15 for(i=0; i<n; i++) 16 { 17 scanf("%d",&num[i]) ; 18 sum += num[i] ; 19 } 20 for(i=0; i<n; i++) 21 { 22 for(j = sum/2; j >= num[i]; j--) 23 { 24 dp[j] = max(dp[j], dp[j-num[i]]+num[i]) ; 25 } 26 } 27 printf("%d\n", sum - 2*dp[sum/2]) ; 28 } 29 return 0 ; 30 }
//搜索真难懂,摘自讨论区:
1 #include <iostream> 2 #include <string> 3 #include <stdio.h> 4 #include <algorithm> 5 #include <stdlib.h> 6 using namespace std; 7 8 const int WATER_MELON = 25; 9 const int MAX_WEIGHT = 10005; 10 11 int n;//西瓜个数 12 int sum; 13 int w[WATER_MELON]; 14 int result; 15 16 bool HandleEachCase(); 17 18 int main() 19 { 20 while(HandleEachCase()) 21 { 22 //empty while 23 } 24 } 25 26 void dfs(int iStep, int iSum); 27 28 bool HandleEachCase() 29 { 30 if(!(cin>>n)) 31 return false; 32 sum = 0; 33 for(int i= 0; i< n; ++i) 34 { 35 cin>>w[i]; 36 sum+=w[i]; 37 } 38 result = sum; 39 dfs(0, 0); 40 cout<<result<<endl; 41 return true; 42 } 43 44 void dfs(int iStep, int iSum) 45 { 46 if(iSum >= (sum>>1) && abs(sum - (iSum<<1))>= result) //比当前最优解要差 47 return; 48 if(iStep == n) 49 {//当前的最优解 50 /*result = abs(sum - (iSum<<1));*/ 51 if(abs(sum-(iSum<<1))< result) 52 result = abs(sum-(iSum<<1)); 53 return; 54 } 55 dfs(iStep+1, iSum+w[iStep]); 56 dfs(iStep+1, iSum); 57 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4671531.html