zoukankan      html  css  js  c++  java
  • 51 nod | 1007 正整数分组(背包DP)

    补题链接:Here

    将一堆正整数分为2组,要求2组的和相差最小。

    例如:1 2 3 4 5,将1 2 4分为1组,3 5分为1组,两组和相差1,是所有方案中相差最少的。

    输入

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

    输出

    输出这个最小差
    

    由于是需要分为两堆,所以可以先统计数组和,然后两堆的总和尽量靠近 sum / 2

    换言之这是一道背包DP

    AC 代码

    #include <bits/stdc++.h>
    using namespace std;
    using ll = long long;
    int dp[100001];
    int a[101];
    int main() {
        int n, s = 0;
        cin >> n;
        for (int i = 1; i <= n; ++i) {
            cin >> a[i];
            s += a[i];
        }
        int m = (s + 1) / 2;
        for (int i = 1; i <= n; ++i)
            for (int j = m; j >= a[i]; --j)
                dp[j] = max(dp[j - a[i]] + a[i], dp[j]);
        cout << abs(s - dp[m] * 2);
        return 0;
    }
    

    The desire of his soul is the prophecy of his fate
    你灵魂的欲望,是你命运的先知。

  • 相关阅读:
    android system.img
    ab压力测试和CC预防
    ubuntu工具积累
    ViewManager
    PopupWindow
    singleton注意
    java byte[]生成
    java有符号无符号的转换
    C#垃圾回收Finalize 和Dispose的理解
    Silverlight 获取汉字拼音首字母
  • 原文地址:https://www.cnblogs.com/RioTian/p/14608201.html
Copyright © 2011-2022 走看看