1007 正整数分组

1007 正整数分组

基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题

将一堆正整数分为2组,要求2组的和相差最小。
例如:1 2 3 4 5,将1 2 4分为1组,3 5分为1组,两组和相差1,是所有方案中相差最少的。
 

Input

第1行:一个数N,N为正整数的数量。 第2 - N+1行,N个正整数。 (N <= 100, 所有正整数的和 <= 10000)

Output

输出这个最小差

Input示例

5

1

2

3

4

5

Output示例

1

 

 

//题解:因为数据范围极小,所以是dp的简单变动,先算出可以组成哪些数,然后,枚举一下所有情况即可

 1 #include<iostream>
 2 #include<cmath>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cstdio>
 6 #include<vector>
 7 using namespace std;
 8 #define INF 0x3f3f3f3f
 9 #define N 1005
10 
11 int num[N];
12 int dp[10005];
13 
14 int main()
15 {
16     int n;
17     scanf("%d",&n);
18     int all=0;
19     for (int i=1;i<=n;i++)
20     {
21         scanf("%d",&num[i]);
22         all+=num[i];
23     }
24     int ut = all/2;
25     dp[0]=1;
26     for (int i=1;i<=n;i++)
27     {
28         for (int j=ut;j>=num[i];j--)
29         {
30             if (dp[j-num[i]]) dp[j]=1;
31         }
32     }
33     int ans = INF;
34     for (int i=1;i<=ut;i++)
35     {
36         if (dp[i]) ans=min(ans,(all-i)-i);
37     }
38     printf("%d\n",ans);
39     return 0;
40 }
View Code

 

 

 

posted @ 2017-09-04 18:01  happy_codes  阅读(388)  评论(0编辑  收藏  举报