题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1007
将一堆正整数分为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 5Output示例
1类似于背包问题。背包的容量为sum/2. sum是所有数的和
#include<stdio.h> #include<algorithm> #include<string.h> #include<queue> #include<math.h> using namespace std; const int maxn = 110; const int inf = 0x3f3f3f3f; typedef long long ll; int n; int a[maxn]; int dp[maxn][maxn*maxn]; //前i个物品,容量为j的最大价值 int main() { //freopen("C://input.txt", "r", stdin); scanf("%d", &n); int sum = 0; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); sum += a[i]; } int tot = sum; sum /= 2; for (int i = 1; i <= n; i++) { for (int j = sum; j >=0; j--) { if (j - a[i] >= 0) { dp[i][j] = max(dp[i - 1][j], dp[i-1][j - a[i]] + a[i]); } else { dp[i][j] = dp[i - 1][j]; } } } printf("%d\n", tot - 2 * dp[n][sum]); return 0; }
51nod 1007 正整数分组(dp)
猜你喜欢
转载自blog.csdn.net/Evildoer_llc/article/details/82976358
今日推荐
周排行