解析: 变相的背包问题,题目要就两人分得到金币差值最小,其实也就是其中分得较少的一人最大可能的接近平均值。
也就是背包容量为sum/2的背包问题。
不过别人的做法都是列举每一种金币总值的可能性,以后再说吧。。。。
1 #include <iostream> 2 #include <string.h> //to use the memset() function 3 using namespace std; 4 #define N 102 //the possible quantity 5 #define M 30005 //the possible value 6 int main() 7 { 8 int dp[M], i, j; 9 int m, k, sum, t; 10 int w[N]; 11 cin>>k; 12 while(k--){ 13 cin>>m; 14 sum = 0; 15 for(i = 1; i <= m; i++){ 16 cin>>w[i]; 17 sum += w[i]; 18 } 19 t = sum / 2; //let one have 'sum'/2 value. 20 memset(dp, 0, sizeof(dp)); 21 for(i = 1; i <= m; i++) //faceing the i'th things 22 for(j = t; j >= 0; j--){ //caculate the best value for every possible capacity 23 if(j >= w[i]){ //chosing the best way 24 if(dp[j] < dp[j - w[i]] + w[i]) 25 dp[j] = dp[j - w[i]] + w[i]; 26 } 27 } 28 t = sum - 2 * dp[t]; 29 cout<<t<<endl; 30 } 31 return 0; 32 }