The stamp is half yours.Time Limit: 1000 MS | memory limit: 65535 kb difficulty: 3
-
Description
-
Xiao Ke recently collected some stamps and he wants to give some of them to his good friend James. Each stamp has a score. They want to divide the stamps into two copies, in addition, the scores and differences between the two stamps are minimized (that is, the scores of the stamps obtained by Xiao Ke and the differences between Xiao Ming are the least). Now the scores of each stamp are known, and they have already scored well, do you know the difference between the stamps they get at the end?
-
Input
-
The first row has only one integer m (M <= 1000), indicating the number of test data groups.
Next there is an integer n (n <= 1000), indicating the number of stamps.
Then there are n integers VI (VI <= 100), indicating the I stamp score.
-
Output
-
Output difference. Each group of outputs occupies one row.
-
Sample Input
-
252 6 5 8 932 1 5
-
Sample output
-
02
-
Source
-
Original
-
Uploaded
-
ACM _ Yang yanxi
-
Solution: sum all the values and fold them to half, and then solve the problem with a 01 backpack.
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #define LL long long10 using namespace std;11 int w[1001];12 int dp[100010];13 int main(){14 int kase,n,i,j,sum,avg;15 scanf("%d",&kase);16 while(kase--){17 scanf("%d",&n);18 sum = 0;19 for(i = 1; i <= n; i++){20 scanf("%d",w+i);21 sum += w[i];22 }23 avg = sum/2;24 memset(dp,0,sizeof(dp));25 for(i = 1; i <= n; i++){26 for(j = avg; j >= w[i]; j--)27 dp[j] = max(dp[j],dp[j-w[i]]+w[i]);28 }29 printf("%d\n",abs(2*dp[avg]-sum));30 }31 return 0;32 }View code